Search code examples
pythondictionarydefaultdict

Is there a better way to merge two dicts of sets?


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?


Solution

  • You are using defaultdicts. 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 updated. That's exactly the use-case for defaultdicts...