簡體   English   中英

從包含列表的字典創建多個字典

[英]Create multiple dictionaries from a dictionary containing lists

我有一本包含列表的字典。 我想從中創建多個字典。

原文是{'user': ['BEBR', 'FRPA', 'GEMU'], 'udp': ['COLT_BE_8845-udp', 'COLT_FR_8845-udp', 'COLT_DE_8845-udp']}

我想要這樣的東西

[{'user': 'BEBR', 'udp': 'COLT_BE_8845-udp'},
{'user': 'FRPA', 'udp': 'COLT_FR_8845-udp'},
{'user': 'GEMU', 'udp': 'COLT_DE_8845-udp'},
....]

這里有一個沙箱

你可以做

res = [{'user':user,'udp':udp} for user, udp in zip(*d.values())]

其中d是您的原始字典

試試下面的代碼:

result = []
for user, udp in zip(original['user'], original['udp']):
    result.append({'user': user, 'udp':udp})

這將返回字典列表,如您的示例所示。

您可以將dictzip一起使用:

d = {'user': ['BEBR', 'FRPA', 'GEMU'], 'udp': ['COLT_BE_8845-udp', 'COLT_FR_8845-udp', 'COLT_DE_8845-udp']}
result = [dict(j) for j in zip(*[[(a, i) for i in b] for a, b in d.items()])]

輸出:

[{'user': 'BEBR', 'udp': 'COLT_BE_8845-udp'}, {'user': 'FRPA', 'udp': 'COLT_FR_8845-udp'}, {'user': 'GEMU', 'udp': 'COLT_DE_8845-udp'}]

您可以使用zip

out=[]
>>> for key,value in zip(dic['user'],dic['udp']):
    out.append({'user':key,'udp':value})
# finds the list in the csvfile dictionary with the key "user"
# the program uses this value to define the length of all list key values in the dictionary
listlength = len(csvfile["user"])

# extract list of keys e.g. user, udp
keys = [key for key in csvfile]

main_list = []
for x in range(listlength):
 sub_dictionary = {}
 for key in keys:
   sub_dictionary[key] = csvfile[key][x]
 main_list.append(sub_dictionary)
print(main_list)

或等價物

csvdict = [{key: csvfile[key][value] for key in [key for key in csvfile]} for value in range(len(csvfile["user"]))]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM