I have dict
:
D = {'a': ['1a', '2a', '3a'], 'c': ['1c', '2c', '3c'], 'b': ['1b', '2b', '3b']}
I want to convert D
to list
of dict
:
L = [{'a':'1a', 'b': '1b', 'c': '1c'}, {'a':'2a', 'b': '2b', 'c': '2c'}, ...]
I tried:
>>> l = [(k, v) for k, vals in D.items() for v in vals]
>>> map(dict, zip(*zip(*[iter(l)]*4)))
[{'a': '1a', 'c': '1c', 'b': '1b'}, {'a': '2a', 'c': '2c', 'b': '2b'}, ...
I need more readable solution.
How about this:
L = [dict(zip(D.keys(), vals)) for vals in zip(*D.values())]
Output:
>>> print L
[{'a': '1a', 'c': '1c', 'b': '1b'},
{'a': '2a', 'c': '2c', 'b': '2b'},
{'a': '3a', 'c': '3c', 'b': '3b'}]
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.