I have a problem with getting values from dictionary. For example, I have the dictionary:
dct={'a':[1,2,3], 'b':[4,5,6], 'c':[7,8,9]}
I want to get each value in each key in order. Output should look like that:
1
4
7
2
5
8
3
6
9
Explanation:
1-first value in key 'a'
4-first value in key 'b'
7-first value in key 'c'
2-second value in key 'a'
5-second value in key 'b'
etc
Thank you in advance!!
I tried this version:
dct={'a':[1,2,3], 'b':[4,5,6], 'c':[7,8,9]}
for key, val in dct.items():
for i in range(len(val)):
print(val[i])
But it didn't work
This should do the trick:
from itertools import chain
result = list(chain(*zip(*dct.values())))
Explanation: we collect values from the dict, zip them, producing something like [(1, 4, 7), (2, 5, 8)...]
and then flatten this list with chain