[英]How to split a dictionary of lists with arbitrary number of values into a list of dictionaries?
我正在嘗試將列表字典拆分為字典列表。
我嘗試按照此處和此處_2的示例進行操作。 Here_2 適用於 python 2.x,似乎不適用於 python 3.x
這里的第一個鏈接示例幾乎可以工作,除了我只將第一個字典鍵值對作為 1 個列表返回。
使用 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}]
這是一個緩慢而脆弱的解決方案,沒有花里胡哨(一般來說命名不好):
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))
當我使用 Python 3 在筆記本上運行您的代碼時,它會打印您作為所需輸出放置的行。 Perharps 我不太明白這個問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.