Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I turn a dictionary with lists as values into a list of dictionaries with single values?

I have this dict:

{
  'x': [0,1,2],
  'y': ['a','b','c']
}

A dictionary where all the values are lists, of identical length.

I want to produce this:

[
  { 'x': 0, 'y': 'a' },
  { 'x': 1, 'y': 'b' },
  { 'x': 2, 'y': 'c' }
]

Is there an efficient way to do this? Hopefully using something in itertools?

like image 602
Cera Avatar asked Jan 01 '26 01:01

Cera


2 Answers

[dict(zip(d, vals)) for vals in zip(*d.values())]

For example:

>>> d = {'y': ['a', 'b', 'c'], 'x': [0, 1, 2]}
>>> [dict(zip(d, vals)) for vals in zip(*d.values())]
[{'y': 'a', 'x': 0}, {'y': 'b', 'x': 1}, {'y': 'c', 'x': 2}]
like image 84
David Robinson Avatar answered Jan 02 '26 13:01

David Robinson


[dict(stuff) for stuff in zip(*[[(k, v) for v in vs] for k, vs in myDict.iteritems()])]
like image 20
BrenBarn Avatar answered Jan 02 '26 13:01

BrenBarn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!