-1

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.

nettux
  • 5,270
  • 2
  • 23
  • 33

1 Answers1

2

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
sshashank124
  • 31,495
  • 9
  • 67
  • 76