在python中转置(转动)列表的字典

Bil*_*tor 5 python dictionary transpose pivot nested

我有一个字典,看起来像:

{'x': [1, 2, 3], 'y': [4, 5, 6]}
Run Code Online (Sandbox Code Playgroud)

我想将其转换为以下格式:

[{'x': 1, 'y': 4}, {'x': 2, 'y': 5}, {'x': 3, 'y': 6}] 
Run Code Online (Sandbox Code Playgroud)

我可以通过显式循环来做到这一点但是有一个很好的pythonic方法吗?

编辑:原来有一个类似的问题在这里和一个答案是一样的在这里接受的答案,但这个答案的作者写道:"我不会容忍任何一种真正的系统的使用这种代码的".有人可以解释为什么这样的代码是坏的?它看起来非常优雅.

Mar*_*ers 11

使用zip()几次,只要字典在两者之间没有发生变异,就可以dict.items()直接在dict返回元素上以相同的顺序迭代这两个事件:

[dict(zip(d, col)) for col in zip(*d.values())]
Run Code Online (Sandbox Code Playgroud)

zip(*d.values())调用转换列表值,并且该zip(d, col)调用再次将每列与字典中的键配对.

以上相当于手动拼写密钥:

[dict(zip(('x', 'y'), col)) for col in zip(d['x'], d['y'])]
Run Code Online (Sandbox Code Playgroud)

无需手动拼出密钥.

演示:

>>> d = {'x': [1, 2, 3], 'y': [4, 5, 6]}
>>> [dict(zip(d, col)) for col in zip(*d.values())]
[{'x': 1, 'y': 4}, {'x': 2, 'y': 5}, {'x': 3, 'y': 6}]
Run Code Online (Sandbox Code Playgroud)