[英]How to split a dictionary of lists with arbitrary number of values into a list of dictionaries?
I am trying to split a dictionary of lists into a list of dictionaries.我正在尝试将列表字典拆分为字典列表。
I have tried following the examples here and here_2 .我尝试按照此处和此处_2的示例进行操作。 Here_2 is for python 2.x and does not seem to work on python 3.x
Here_2 适用于 python 2.x,似乎不适用于 python 3.x
The first linked example, here, almost works except I only get the first dictionary key value pair back as 1 list.这里的第一个链接示例几乎可以工作,除了我只将第一个字典键值对作为 1 个列表返回。
using zip() to convert dictionary of list to list of dictionaries使用 zip() 将列表字典转换为字典列表
test_dict = { "Rash" : [1], "Manjeet" : [1], "Akash" : [3, 4] }
res = [dict(zip(test_dict, i)) for i in zip(*test_dict.values())]
print ("The converted list of dictionaries " + str(res))
Out: The converted list of dictionaries [{‘Rash’: 1, ‘Akash’: 3, ‘Manjeet’: 1}]
DESIRED Out: The converted list of dictionaries [{‘Rash’: 1, ‘Akash’: 3, ‘Manjeet’: 1}, {‘Akash’: 4}]
Here's a slow and brittle solution with no bells or whistles (and bad naming in general):这是一个缓慢而脆弱的解决方案,没有花里胡哨(一般来说命名不好):
def dictlist_to_listdict(dictlist):
output = []
for k, v in dictlist.items():
for i, sv in enumerate(v):
if i >= len(output):
output.append({k: sv})
else:
output[i].update({k: sv})
return output
if __name__ == "__main__":
test_dict = {"Rash": [1], "Manjeet": [1], "Akash": [3, 4]}
print(dictlist_to_listdict(test_dict))
When I ran your code on my notebook with Python 3, it does print the line you put as the desired output.当我使用 Python 3 在笔记本上运行您的代码时,它会打印您作为所需输出放置的行。 Perharps I don't understand the question well enough
Perharps 我不太明白这个问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.