Skip to content

Instantly share code, notes, and snippets.

@noahlias
Last active June 5, 2023 16:33
Show Gist options
  • Save noahlias/02f5c66f6ad082c430d4d6df8a3715d8 to your computer and use it in GitHub Desktop.
Save noahlias/02f5c66f6ad082c430d4d6df8a3715d8 to your computer and use it in GitHub Desktop.
Some Research about python dict merge.
test_a = {'country':'China','state':None}
test_b = {'country': None,'state':'Beijing'}

Unpack and Merge

Reference

filter_test_a = dict(filter(lambda item: item[1] is not None, test_a.items()))
filter_test_b = dict(filter(lambda item: item[1] is not None, test_b.items()))
dict_comprehension_test_a = dict((key, value) for key, value in test_a.items() if value is not None)
dict_comprehension_test_b = dict((key, value) for key, value in test_b.items() if value is not None)
{**filter_test_a, **filter_test_b}
{'country': 'China', 'state': 'Beijing'}

Merge Dictionaries by Union Operator

filter_test_a | filter_test_b
{'country': 'China', 'state': 'Beijing'}
dict_comprehension_test_a | dict_comprehension_test_b
{'country': 'China', 'state': 'Beijing'}

Update Function

res = filter_test_a.copy()
res.update(filter_test_b)
res
{'country': 'China', 'state': 'Beijing'}

Expand two much more dict

code is generated by ChatGPT.

from typing import Dict, Any

def merge_dicts(*dicts: Dict[str, Any]) -> Dict[str, Any]:
    filtered_dict = {}
    for dictionary in dicts:
        for key, value in dictionary.items():
            if value is not None:
                filtered_dict[key] = value
    return filtered_dict
dict1 = {"key1": "value1", "key2": None, "key3": "value3"}
dict2 = {"key2": "value2", "key4": None}
dict3 = {"key1": None, "key4": "value4"}

merged_dict = merge_dicts(dict1, dict2, dict3)
print(merged_dict)
{'key1': 'value1', 'key3': 'value3', 'key2': 'value2', 'key4': 'value4'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment