我正在尝试一一阅读字典中的所有元素。我的字典如下“测试”所示。
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
谢谢你
我正在尝试一一阅读字典中的所有元素。我的字典如下“测试”所示。
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
谢谢你
#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()
按值迭代字典这里有几种可能性。你的问题很模糊,你的代码甚至还没有接近工作,所以很难理解这个问题
>>> 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
试试这个:
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
您可以使用嵌套理解:
>>> 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 中是未排序的,因此您的元组也将是未排序的。