简体   繁体   中英

Create multiple dictionaries from a dictionary containing lists

I have a dictionary that contains lists. I want to create multiple dictionaries from it.

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

and I want something like this

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

i have a sandbox here

You can do

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

where d is your original dictionary

Try the following code:

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

This would return a list of dictionaries, as in your example.

You can use dict with zip :

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()])]

Output:

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

You can use 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)

or the equivalent

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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