Home > front end >  python flatten dict with leaving the same key name after flatten
python flatten dict with leaving the same key name after flatten

Time:04-21

I have the following dict:


{
"a": "b",
"c": {'d':'e', 'g':'f'}
}

and I want to flatten the dict, but in this way:

{
"a": "b",
'd':'e',
'g':'f'
}

You can assume there is no duplicate key.

I read about flatten_dict library but it looks there is no support in this.

How can I do this? Thank you!

CodePudding user response:

For one level of nesting, a nice loop does the trick:

result = {}
for key, value in my_dict.items():
    if isinstance(value, dict):
        result.update(value)  # add subdict directly into the dict
    else:
        result[key] = value  # non-subdict elements are just copied

If you have more nesting, the if/else should be executed recursively:

def flatten(my_dict):
    result = {}
    for key, value in my_dict.items():
        if isinstance(value, dict):
            result.update(flatten(value))
        else:
            result[key] = value 
    return result

CodePudding user response:

You can use a modified version of this answer:

from collections.abc import MutableMapping

def flatten(d):
    items = []
    for k, v in d.items():
        if isinstance(v, MutableMapping):
            items.extend(flatten(v).items())
        else:
            items.append((k, v))
    return dict(items)
>>> x = {
...     "a": "b",
...     "c": {'d': 'e', 'g': 'f'}
... }
>>> flatten(x)
{'a': 'b', 'd': 'e', 'g': 'f'}

This will work for all forms of any dictionary

  • Related