我有dict

D = {'a': ['1a', '2a', '3a'], 'c': ['1c', '2c', '3c'], 'b': ['1b', '2b', '3b']}


我想将D转换为listdict

L = [{'a':'1a', 'b': '1b', 'c': '1c'}, {'a':'2a', 'b': '2b', 'c': '2c'}, ...]


我试过了:

>>> 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'}, ...


我需要更具可读性的解决方案。

最佳答案

这个怎么样:

L = [dict(zip(D.keys(), vals)) for vals in zip(*D.values())]


输出:

>>> print L
[{'a': '1a', 'c': '1c', 'b': '1b'},
 {'a': '2a', 'c': '2c', 'b': '2b'},
 {'a': '3a', 'c': '3c', 'b': '3b'}]

关于python - 如何从列表的字典创建字典列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25200766/

10-12 13:31