在 Python 中操作字典 [英] Manipulating dictionaries in Python

查看:22
本文介绍了在 Python 中操作字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储月份的字典:

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

我有一个 while 循环,循环了 12 次(一年):

And I have a while loop, that loops 12 times (one year):

(伪)

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.

推荐答案

我的意思是使用 while 循环(while 循环在 python 中很少用于迭代), 那么为此你需要一个反向散列或字典

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

更好的实现是使用 for 循环 -

A better implementation would be using for loop -

for month in range(1, 13):
    print(reverse_months[month])

虽然,首先为什么你需要 looping,我想你可以很容易地使用迭代器,除非你的用例与你的代码建议的有很大不同.

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)

附言- 请仔细阅读 Pep 8 指南,了解 Python 中的命名约定

P.S. - Please go through Pep 8 guidelines too for naming conventions in python

这篇关于在 Python 中操作字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆