sprint_6
sprint_6

Reputation: 81

Iterate through lists in values of all keys in a dictionary in parallel?

Hello I have a python dictionary that looks like this:

d = {'a': [1,2,3],
     'b': [3,4,5],
     'c':[6,7,8]}

Is there any way to iterate through this dictionary so that I am getting each item in all list value in all keys in order in parallel? Keep in mind I don't have pandas package available.

So for example:

loop 1 output: a:1,b:3,c:6
loop 2 output: a:2,b:4,c:7
loop 3 output: a:3,b:5,c:8

You can assume the list lengths are going to be the same for all keys in the dictionary.

Upvotes: 0

Views: 575

Answers (1)

Reti43
Reti43

Reputation: 9797

As a one-liner

result = [dict(zip(d.keys(), v)) for v in zip(*d.values())]

Or if you want to split things up to make it a bit clearer

keys, values = d.keys(), list(zip(*d.values()))
result = [dict(zip(keys, v)) for v in values]

Upvotes: 5

Related Questions