0

I would like to flatten a nested dictionary. A solution for such a problem was suggested here: https://stackoverflow.com/a/41801708/8443371. Problem: I would like to obtain a keys identical to the keys in the last layer only. For an input:

d = {'a': 1,
     'c': {'b': {'x': 5,
                 'y' : 10}},
     'd': [1, 2, 3]}

I would like to have an output:

{'a': 1, 'x': 5, 'y': 10, 'd': [1, 2, 3]}

Suggestions using python only should be probably slower than Pandas, which is based on a C implementation.

Note: Assuming max two layer dictionary, I have a python solution, which seems to be very slow:

for key in dict.keys():
    if '.' in key:
       dict[key.split('.')[-1]] = dict.pop(key)
Gideon Kogan
  • 662
  • 4
  • 18

1 Answers1

2

Here's my solution in pure python for the dictionary you've provided:

d = {'a': 1,
     'c': {'b': {'x': 5,
                 'y' : 10}},
     'd': [1, 2, 3]}

def flatten_dict(dic):
    result = {}
    for key in dic.keys():
        if isinstance(dic[key], dict):
            result.update(flatten_dict(dic[key]))
        else:
            result[key] = dic[key]
return result

flatten_dict(d)
{'a': 1, 'x': 5, 'y': 10, 'd': [1, 2, 3]}

%%timeit
flatten_dict(d)
2.45 µs ± 72.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Mohit Motwani
  • 4,662
  • 3
  • 17
  • 45