How To Create A Dictionary Merging Values Based On Keys?
I need to create a dictionary mapping a keys to merged values. Let's say I got key value pairs with a duplicated key 40: {40: 'lamb'}, {40: 'dog'}, {50: 'chicken'} list_key = (40,
Solution 1:
One way is to create a list if the key doesn't exist. Then, just append to that list whenever you encounter a relevant key.
keys = [40, 40, 50]
values = ["lamb", "dog", "chicken"]
d = {}
for k, v in zip(keys, values):
if k not in d:
d[k] = []
d[k].append(v)
...Though you can do this more prettily with collections.defaultdict
:
keys = [40, 40, 50]
values = ["lamb", "dog", "chicken"]
d = defaultdict(lambda: [])
for k, v in zip(keys, values):
d[k].append(v)
Post a Comment for "How To Create A Dictionary Merging Values Based On Keys?"