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
?
[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}]
[dict(stuff) for stuff in zip(*[[(k, v) for v in vs] for k, vs in myDict.iteritems()])]
[{'x': v, 'y': d['y'][i]} for i, v in enumerate(d['x'])]
d = {
'x': [0,1,2],
'y': ['a','b','c']
}
values = zip(*d.values())
print [dict(zip(d.keys(), v)) for v in values]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.