如何在python中迭代字典?

2024-03-28 23:13:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试着把字典里的所有元素一一读出来。我的字典如下“测试”。在

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

我想按照下面的示例代码来做。在

^{pr2}$

谢谢你


Tags: 代码test元素示例字典line1pr2line2
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
#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

正在分析代码

^{pr2}$
  1. 你不能索引字典。字典不像列表那样是一个序列
  2. 不要用括号来索引。它变成了一个函数调用
  3. 要迭代字典,可以迭代键或值。
    1. for key in test按键迭代字典
    2. for key in test.values()按值迭代字典

试试这个:

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

如果您需要列表:

^{pr2}$

如果要从dict than打印每条记录:

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

相关问题 更多 >