从字典中获取密钥

时间:2011-06-29 08:35:38

标签: python dictionary

我刚开始使用Python,

在PHP中是否存在一些迭代

foreach(aData as key=>value)

3 个答案:

答案 0 :(得分:9)

它看起来像这样:

my_dict = {"key1": 1, "key2":2}
my_dict.items()       # in python < 3 , you should use iteritems()
>>> ("key1", 1), ("key2", 2)

所以你可以迭代它:

for key, value in my_dict.items():
   do_the_stuff(key, value)

答案 1 :(得分:5)

假设python 2:

for key, value in aData.iteritems():

答案 2 :(得分:4)

使用:

for key in dictionary.keys()
    value = dictionary[key]
    #do something

或者:

for key,value in dictionary.items():
    #do something