如何在python中迭代字典?

时间:2013-03-28 05:13:07

标签: python dictionary python-2.7

我试图逐个阅读字典中的所有元素。我的字典如下“测试”所示。

test ={'line4': (4, 2), 'line3': (3, 2), 'line2': (2, 2), 'line1': (1, 2), 'line10': (10, 2)}

我想按照以下示例代码中的说明进行操作。

for i in range(1,len(test)+1):
    print test(1) # should print all the values one by one

谢谢

4 个答案:

答案 0 :(得分:3)

#Given a dictionary
>>> test ={'line4': (4, 2), 'line3': (3, 2), 'line2': (2, 2), 'line1': (1, 2), 'line10': (10, 2)}

#And if you want a list of tuples, what you need actually is the values of the dictionary
>>> test.values()
[(4, 2), (3, 2), (2, 2), (1, 2), (10, 2)]

#Instead if you want a flat list of values, you can flatten using chain/chain.from_iterable
>>> list(chain(*test.values()))
[4, 2, 3, 2, 2, 2, 1, 2, 10, 2]
#And to print the list 
>>> for v in chain.from_iterable(test.values()):
    print v


4
2
3
2
2
2
1
2
10
2

分析您的代码

for i in range(1,len(test)+1):
    print test(1) # should print all the values one by one
  1. 您无法索引字典。字典不是像列表那样的序列
  2. 你不要用括号来索引。它变成了函数调用
  3. 要迭代字典,您可以迭代键或值。
    1. for key in test按键迭代字典
    2. for key in test.values()按值
    3. 迭代字典

答案 1 :(得分:3)

以下是一些可能性。你的问题很模糊,你的代码甚至没有接近工作,所以很难理解这个问题

>>> test ={'line4': (4, 2), 'line3': (3, 2), 'line2': (2, 2), 'line1': (1, 2), 'line10': (10, 2)}
>>> for i in test.items():
...     print i
... 
('line4', (4, 2))
('line3', (3, 2))
('line2', (2, 2))
('line1', (1, 2))
('line10', (10, 2))
>>> for i in test:
...     print i
... 
line4
line3
line2
line1
line10
>>> for i in test.values():
...     print i
... 
(4, 2)
(3, 2)
(2, 2)
(1, 2)
(10, 2)
>>> for i in test.values():
...     for j in i:
...         print j
... 
4
2
3
2
2
2
1
2
10
2

答案 2 :(得分:2)

试试这个:

for v in test.values():
    for val in v:
        print val

如果您需要一个清单:

print [val for v in test.values() for val in v ]

如果要从dict打印每条记录而不是:

for k, v in test.iteritems():
    print k, v

答案 3 :(得分:1)

您可以使用嵌套理解:

>>> test ={'line4': (4, 2), 'line3': (3, 2), 'line2': (2, 2), 'line1': (1, 2), 'line10': (10, 2)}
>>> print '\n'.join(str(e) for t in test.values() for e in t)
4
2
3
2
2
2
1
2
10
2

由于字典在Python中未被排序,因此您的元组也将被排除。