4

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?

1
  • 4
    A simple recursive version could be enough, but not efficient for big levels of nesting. What did you try already? It is always better to have a starting point in order to help you. Commented Apr 11, 2019 at 3:36

3 Answers 3

6

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}
Sign up to request clarification or add additional context in comments.

6 Comments

flatten_dict not work if list contained in the dict, such as {'b': [{'c':{'d':[1,2,3]}}]}
What output you are expecting in this case? {'b.c.d': [1,2,3]} ??
yes. {'b': [{'c':{'d':[1,2,3]}}, 'e':[{'f':3}, {'g':6}]]} to {'b.c.d':[1,2,3], 'b.e.f':3, 'b.e.g':6}
should not be it something like this.. {'b': [{'c':{'d':[1,2,3]}}, 'e':[{'f':3}, {'g':6}]]} . ---> . {'b_0.c.d':[1,2,3], ''b_1.e_0.f":3, b_1.e_1.g:6} Because list may contain duplicate dictionaries.. indexing also needed in this case?
Flatten_dict does not flat values if values are list.
|
2

There are multiple ways. Here is one way to do it.

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

    flatten_dict = {}

    def flatten_the_nested(nested_dict, parent_key=''):
        for key, value in nested_dict.items():
            new_key = parent_key + '.' + key if parent_key is not '' else key
            if isinstance(value, dict):
                flatten_the_nested(value, new_key)
            else:
                flatten_dict[new_key] = value

        return flatten_dict


     print(flatten_the_nested(nested_dict, ''))

You will get the following result.

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

Or if you want to use some library then you can use https://pypi.org/project/flatten-dict/

Comments

0

Well, its not complicated. In just a few minutes I got the following:

def flatten(dic, prefix = ""):
    if prefix is not "":
        prefix = prefix + "."

    result = {}

    for k, v in dic.iteritems():
        if isinstance(v, dict):
            for k1, v1 in flatten(v, prefix + k).iteritems():
                result[k1] = v1
        else:
            result[prefix + k] = v

    return result

I have not thoroughly tested this algorithm, though.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.