How to Flatten Nested Dictionary in Python Easily
To flatten a nested dictionary in Python, you can use a recursive function that iterates through each key-value pair and combines nested keys into a single key using a separator. This creates a new dictionary with no nested structures, making it easier to access all values directly.
Syntax
Use a recursive function that takes a dictionary and a separator string. The function checks if a value is a dictionary; if yes, it calls itself with the nested dictionary and updates keys by joining parent and child keys with the separator. Otherwise, it adds the key-value pair to the result.
python
def flatten_dict(d, parent_key='', sep='_'): items = {} for k, v in d.items(): new_key = f"{parent_key}{sep}{k}" if parent_key else k if isinstance(v, dict): items.update(flatten_dict(v, new_key, sep=sep)) else: items[new_key] = v return items
Example
This example shows how to flatten a nested dictionary with two levels. The keys from inner dictionaries are joined with outer keys using an underscore.
python
def flatten_dict(d, parent_key='', sep='_'): items = {} for k, v in d.items(): new_key = f"{parent_key}{sep}{k}" if parent_key else k if isinstance(v, dict): items.update(flatten_dict(v, new_key, sep=sep)) else: items[new_key] = v return items nested = { 'person': { 'name': 'Alice', 'age': 30 }, 'job': { 'title': 'Engineer', 'department': 'Development' } } flat = flatten_dict(nested) print(flat)
Output
{'person_name': 'Alice', 'person_age': 30, 'job_title': 'Engineer', 'job_department': 'Development'}
Common Pitfalls
One common mistake is not handling nested dictionaries recursively, which results in only the first level being flattened. Another is using mutable default arguments or not choosing a clear separator, which can cause key collisions or confusing keys.
python
def wrong_flatten(d): flat = {} for k, v in d.items(): if isinstance(v, dict): # This only adds the nested dict as is, not flattening it flat[k] = v else: flat[k] = v return flat nested = {'a': {'b': 1}} print(wrong_flatten(nested)) # Output: {'a': {'b': 1}} # Not flattened # Correct way uses recursion as shown in previous example
Output
{'a': {'b': 1}} # Not flattened
Quick Reference
- Use recursion to handle any depth of nesting.
- Choose a separator like underscore (_) or dot (.) for joined keys.
- Check if a value is a dictionary before recursing.
- Return a new dictionary with flattened keys and values.
Key Takeaways
Flatten nested dictionaries by recursively joining keys with a separator.
Always check if a value is a dictionary before recursing to avoid errors.
Use a clear separator to keep keys readable and avoid collisions.
Avoid mutable default arguments in recursive functions.
Test your function with different nesting depths to ensure correctness.