问题描述
我有一本可以存储月份的字典:
Months = {'一月':1,'二月':2,'三月':3,'四月':4,'五月':5,'六月':6,6,七月':7,八月":8,九月":9,十月":10,十一月":11,十二月":12
我有一个while循环,它循环12次(一年):
(伪)
Month = 1决赛= 12而月份< =最终:在此处致电Month_from_dictionary_as_string_here月+ = 1
如何根据另一个变量的值调用字典键?谢谢.
我的意思是使用 while
循环( while
循环很少用于python中的迭代),那么您需要为此目的使用反向哈希或字典
reverse_months = {value:键的键,Months.items()中的值}print(reverse_months [1])#一月
更好的实现方式是使用 for
循环-
在范围(1,13)中的月份:打印(reverse_months [month])
尽管,为什么首先需要使用 looping
,但我想您可以轻松地使用迭代器,除非您的用例与您的代码所建议的有很大不同.
,在Months.items()中的值:print(键:{0},值:{1}".格式(键,值)
P.S.-对于python中的命名约定,也请通过 Pep 8准则>
I have a dictionary that stores months:
Months = {'January': 1, 'February': 2, 'March': 3, 'April': 4, 'May': 5, 'June': 6, 'July': 7, 'August': 8, 'September': 9, 'October': 10, 'November': 11, 'December': 12
And I have a while loop, that loops 12 times (one year):
(pseudo)
Month = 1
Final = 12
while Month <= Final:
call Month_from_dictionary_as_string_here
Month += 1
how can I call dictionary keys depending on the value of the other variable? Thanks.
I you are meant on using while
loop(while
loop is seldom used for iteration in python), then you need a reverse hash or dictionary for this purpose
reverse_months = {value: key for key, value in Months.items()}
print(reverse_months[1]) # January
A better implementation would be using for
loop -
for month in range(1, 13):
print(reverse_months[month])
Although, why do you need looping
at all in first place, I guess you can easily make do with an iterator, unless your use case is much different from what your code suggests.
for key, value in Months.items():
print("key: {0}, value: {1}".format(key, value)
P.S. - Please go through Pep 8 guidelines too for naming conventions in python
这篇关于在Python中操作字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!