2013-03-28 93 views
-2

我试图逐个阅读字典中的所有元素。我的字典在下面给出“测试”。如何在Python中迭代字典?

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 

谢谢

+2

这不是一个元组。 – JBernardo 2013-03-28 05:15:30

+1

要清楚:你有一个元组字典。 '{'line4':(4,2)}'是一个元素。 '(4,2)'是映射到'line4'的元组值。 Python字典没有排序。 – dawg 2013-03-28 05:28:28

+0

_Sample output_会加强这个问题,甚至可能使它对本网站有用 – 2013-03-28 05:33:12

回答

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

试试这个:

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

如果你需要一个列表:如果你想从字典打印每个记录比

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

for k, v in test.iteritems(): 
    print k, v 
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()一本词典值
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中无序,你的元组也将被排序。