在python中循环一个未命名的字典

时间:2012-04-11 07:57:12

标签: python for-loop

有没有办法在python中打印匿名字典的键和值。

for key in {'one':1, 'two':2, 'three':3}:
    print key, ":", #value

5 个答案:

答案 0 :(得分:5)

for key, value in {'one':1, 'two':2, 'three':3}.iteritems():
    print key, ":", value

默认情况下,迭代它会返回其键。 .iteritems()返回(key,value)的2元组。

答案 1 :(得分:3)

你可以这样做:

for  (key, value) in {'one':1, 'two':2, 'three':3}.items():
    print key, value

答案 2 :(得分:3)

要迭代键/值对,您可以使用.items().iteritems()

for k, v in {'one':1, 'two':2, 'three':3}.iteritems():
    print '%s:%s' % (k, v)

请参阅http://docs.python.org/library/stdtypes.html#dict.iteritems

答案 3 :(得分:2)

当然,只需使用:

for key,value in {'one':1, 'two':2, 'three':3}.items():
    print key, ":", value

答案 4 :(得分:0)

您可以使用iteritems方法迭代dict

for key, value in {'one':1, 'two':2, 'three':3}.iteritems():
    print key
    print value