简体   繁体   English

将字典列表转换为字典的多维列表

[英]Convert dictionary lists to multi-dimensional list of dictionaries

I've been trying to convert the following: 我一直在尝试转换以下内容:

data = {'title':['doc1','doc2','doc3'], 'name':['test','check'], 'id':['ddi5i'] }

to: 至:

[{'title':'doc1', 'name': 'test', 'id': 'ddi5i'},
{'title':'doc2', 'name': 'test', 'id': 'ddi5i'},
{'title':'doc3', 'name': 'test', 'id': 'ddi5i'},
{'title':'doc1', 'name': 'check', 'id': 'ddi5i'},
{'title':'doc2', 'name': 'check', 'id': 'ddi5i'},
{'title':'doc3', 'name': 'check', 'id': 'ddi5i'}]

I've tried various options (list comprehensions, pandas and custom code) but nothing seems to work. 我尝试了各种选项(列表理解,熊猫和自定义代码),但似乎没有任何效果。 For example, the following: 例如,以下内容:

panda.DataFrame(data).to_dict('list')

throws an error because, since it tries to map the lists, all of them have to be of the same length. 抛出错误是因为,由于它尝试映射列表,因此所有列表必须具有相同的长度。 Besides, the output would only be uni-dimensional which is not what I'm looking for. 此外,输出将只是一维的,这不是我想要的。

itertools.product may be what you're looking for here, and it can be applied to the values of your data to get appropriate value groupings for the new dicts. itertools.product可能就是您在这里寻找的东西,可以将其应用于数据值以获取适用于新字典的适当值分组。 Something like 就像是

list(dict(zip(data, ele)) for ele in product(*data.values()))

Demo 演示

>>> from itertools import product
>>> list(dict(zip(data, ele)) for ele in product(*data.values()))
[{'id': 'ddi5i', 'name': 'test', 'title': 'doc1'},
 {'id': 'ddi5i', 'name': 'test', 'title': 'doc2'},
 {'id': 'ddi5i', 'name': 'test', 'title': 'doc3'},
 {'id': 'ddi5i', 'name': 'check', 'title': 'doc1'},
 {'id': 'ddi5i', 'name': 'check', 'title': 'doc2'},
 {'id': 'ddi5i', 'name': 'check', 'title': 'doc3'}]

It is clear how this works once seeing 很明显,一旦看到,它是如何工作的

>>> list(product(*data.values()))
[('test', 'doc1', 'ddi5i'),
 ('test', 'doc2', 'ddi5i'),
 ('test', 'doc3', 'ddi5i'),
 ('check', 'doc1', 'ddi5i'),
 ('check', 'doc2', 'ddi5i'),
 ('check', 'doc3', 'ddi5i')]

and now it is just a matter of zipping back into a dict with the original keys. 现在只需要将原始键压缩回字典即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM