PYTHON

Combine and Filter Dictionaries in Python

Learn modern Python techniques for merging two dictionaries into one and efficiently filtering dictionary items based on conditions for keys or values, vital for data processing.

dict1 = {'name': 'Alice', 'age': 30, 'city': 'New York'}
dict2 = {'city': 'San Francisco', 'occupation': 'Engineer'}
dict3 = {'status': 'active', 'age': 25}

# Merging dictionaries (Python 3.9+ using | operator)
merged_dict_union = dict1 | dict2
print(f"Merged using | (dict1 | dict2): {merged_dict_union}")

# Merging dictionaries (older Python versions or alternative)
# The right-hand dictionary's values override the left's if keys overlap.
merged_dict_unpack = {**dict1, **dict2}
print(f"Merged using ** ({{\**dict1, \**dict2}}): {merged_dict_unpack}")

# Merging multiple dictionaries
merged_multiple = {**dict1, **dict2, **dict3}
print(f"Merged multiple: {merged_multiple}")

# Filtering a dictionary by key
filtered_by_key = {k: v for k, v in merged_multiple.items() if k != 'city'}
print(f"Filtered by key (removed 'city'): {filtered_by_key}")

# Filtering a dictionary by value
filtered_by_value = {k: v for k, v in merged_multiple.items() if isinstance(v, str)}
print(f"Filtered by value (only strings): {filtered_by_value}")

# Filtering based on a condition (e.g., age > 28)
data = {'john': 25, 'mary': 32, 'peter': 28, 'susan': 35}
older_users = {name: age for name, age in data.items() if age > 28}
print(f"Users older than 28: {older_users}")
How it works: Dictionaries are fundamental for key-value data storage. Python 3.9+ introduced the `|` operator for cleaner merging, where values from the right-hand dictionary overwrite those from the left on key collision. For older versions or alternative syntax, the `**` unpacking operator achieves similar results. Dictionary comprehensions offer a concise way to filter dictionary items based on conditions applied to keys or values, making data manipulation efficient.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs