Flattening Nested Dictionaries: Compressing Keys
To flatten a nested dictionary, you'll need to recursively iterate through each key and value pair, creating new keys by concatenating the parent key with the current key using a separator, such as an underscore.
Deeper levels of the nested dictionary require further recursion using the same process.
Once you've completed the recursion, create a new dictionary from the flattened items.
Here's an example implementation using Python's collections.abc.MutableMapping:
from collections.abc import MutableMapping def flatten(dictionary, parent_key='', separator='_'): items = [] for key, value in dictionary.items(): new_key = parent_key + separator + key if parent_key else key if isinstance(value, MutableMapping): items.extend(flatten(value, new_key, separator=separator).items()) else: items.append((new_key, value)) return dict(items)
Example usage:
>>> flatten({'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]}) {'a': 1, 'c_a': 2, 'c_b_x': 5, 'd': [1, 2, 3], 'c_b_y': 10}
The above is the detailed content of How Do I Flatten a Nested Dictionary in Python?. For more information, please follow other related articles on the PHP Chinese website!