#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
- 不能索引字典。字典不是像列表那样的序列
- 您不要使用括号来进行索引。它变成一个函数调用
- 要迭代字典,您可以迭代键或值。
for key in test
迭代通过键
for key in test.values()
一本词典值
这不是一个元组。 – JBernardo 2013-03-28 05:15:30
要清楚:你有一个元组字典。 '{'line4':(4,2)}'是一个元素。 '(4,2)'是映射到'line4'的元组值。 Python字典没有排序。 – dawg 2013-03-28 05:28:28
_Sample output_会加强这个问题,甚至可能使它对本网站有用 – 2013-03-28 05:33:12