Merge Multiple Dictionaries When Their Keys Have A List Of Values Python
I came across a post that had a complete and correct way of merging two dictionaries, when each dictionary has for each key a list of values. The input of the program is something
Solution 1:
There is no need to iterate over pairs of dictionaries, as set().union() operation can take multiple arguments:
defmerge_dictionaries(*args):
result = {}
for key inset().union(*args):
# let's convert the value union to set before sorting to get rid of the duplicates
result[key] = sorted(set.union(*[set(d.get(key, [])) for d in args]), key=int)
return result
Solution 2:
You have a typo: you used dict
where you meant dicts
.
Post a Comment for "Merge Multiple Dictionaries When Their Keys Have A List Of Values Python"