Given a list of dictionaries in python like this:

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. 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

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归因
不隶属于 StackOverflow
scroll top