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?
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With