I am using this code to merge one dict into another - if a key exists, it should merge the values from both dicts:
source_dict = defaultdict(set)
target_dict = defaultdict(set)
def merge_dict(source_dict, target_dict):
for source_key in source_dict:
if source_key in target_dict:
target_dict[source_key].update(source_dict[source_key])
else:
target_dict[source_key] = source_dict[source_key]
Is there a way to optimize the merge_dict
function above? For example, to make it more concise or more efficient?
CodePudding user response:
You are using defaultdict
s. So you don't need the if/else
... Just do:
def merge_dict(source_dict, target_dict):
for source_key, source_value in source_dict.items():
target_dict[source_key].update(source_value)
If the source_key
is not in target_dict
, an empty set will be created and immediately update
d. That's exactly the use-case for defaultdict
s...
CodePudding user response:
You could wirte it as an update from a comprehension:
from collections import defaultdict
source_dict = defaultdict(set,{'a':{1,2,3},'b':{4,5,6}})
target_dict = defaultdict(set,{'b':{5,6,7},'c':{8,9}})
target_dict.update((k,s|target_dict[k]) for k,s in source_dict.items())
print(target_dict)
# defaultdict(<class 'set'>, {'b': {4, 5, 6, 7}, 'c': {8, 9}, 'a': {1, 2, 3}})