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}
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3