Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert python nested dict to non-nested dict?

How to convert below src dict (nested dict)

{
    'a':{'b':1, 'c':{'d':2}},
    'b':3,
    'c':{'d':4, 'a':5}
}

to dst dict (not nested) below?

{
    'a.b':1,
    'a.c.d':2,
    'b':3,
    'c.d':4,
    'c.a':5
}

The src dict is nested dict. And the dst dict is not nested dict.

Any easy method to do this convention?

like image 836
ybdesire Avatar asked Jan 27 '23 11:01

ybdesire


1 Answers

This is python package for flatten dictionary. You can use this

https://pypi.org/project/flatten-dict/

Implementation:

from flatten_dict import flatten

nested = {'a': {'b': 1, 'c': {'d': 2}},
          'b': 3,
          'c': {'d': 4, 'a': 5}}

flat = flatten(nested, reducer=lambda k1, k2: k2 if k1 is None else k1 + '.' + k2)
print(flat)
# {'a.b': 1, 'a.c.d': 2, 'b': 3, 'c.d': 4, 'c.a': 5}
like image 178
Jyoti Arora Avatar answered Feb 12 '23 05:02

Jyoti Arora