[英]loop through values from a list of dictionaries in Python
Given a list of dictionaries in python like this: 在python中给出这样的字典列表:
dict_list = [
{'a' : 1, 'b' : 2},
{'c' : 2, 'd' : 3},
{'x' : 4, 'y' : 5, 'z': 0}
]
What is the best to loop through all the values while emulating the obvious: 在模拟显而易见的值时最好遍历所有值:
for i in dict_list:
for x in i.values():
print x
But ideally avoiding the nested for
loops. 但最好避免嵌套的
for
循环。 I'm sure there must be a better way but I can't find it. 我确定必须有更好的方法,但是找不到。
To loop through all the values, use itertools.chain.from_iterable
要遍历所有值,请使用
itertools.chain.from_iterable
from itertools import chain
dict_list = [
{'a' : 1, 'b' : 2},
{'c' : 2, 'd' : 3},
{'x' : 4, 'y' : 5, 'z': 0}
]
for item in chain.from_iterable(i.values() for i in dict_list):
print item
Outputs: 输出:
1
2
2
3
5
4
0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.