Reputation: 304
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
Upvotes: 4
Views: 1403
Reputation: 71451
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'}]
Upvotes: 1
Reputation: 304
# 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"]))]
Upvotes: 0
Reputation: 1176
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.
Upvotes: 1
Reputation: 11929
You can do
res = [{'user':user,'udp':udp} for user, udp in zip(*d.values())]
where d
is your original dictionary
Upvotes: 3