-1

I'm new in Python and currently trying to read the following JSON:

"level1_key1":"1",
"level1_key2":{
    "level2_key1":"2",
    "level2_key2":{
        "level3_key1":"Max depth"
    }
}

then put it in a dictionary (done by now) and finally show it as nested and flatten (I'm using Python 3.6). I want to do it with recursion and avoid using third party libraries. I tried all the suggestions from StackOverflow but can't make the result look like the one from the task which is:

Nested dict: {u'level1_key2': {u'level2_key2': {u'level3_key1': u'Max depth'}, u'level2_key1': u'2'}, u'level1_key1': u'1'}
Flatten dict: {u'level2_key1': u'2', u'level3_key1': u'Max depth', u'level1_key1': u'1'}

I'd much appreciate any help. Thanks in advance!

Aktan A.
  • 1
  • 2

2 Answers2

0

Please try below code. It should solve your query.

example_dict = {"level1_key1":"1",
                    "level1_key2":{
                        "level2_key1":"2",
                        "level2_key2":{
                            "level3_key1":"Max depth"
                        }
                     }
                 }   

flatten_dict = {}
def process_dict(dict_val):
    for key, val in dict_val.items():
        if isinstance(val, dict) and val:
            process_dict(val)
        else:
            flatten_dict.update({key:val})
    return flatten_dict

print process_dict(example_dict)


The Answer:

{'level2_key1': '2', 'level3_key1': 'Max depth', 'level1_key1': '1'}

Subhrajyoti Das
  • 2,685
  • 3
  • 21
  • 36
  • Hello and thanks for your answer. Unfortunately when I try to execute, I get the following error: Traceback (most recent call last): File "file.py", line 73, in print(process_dict(example_dict)) File "file.py", line 64, in process_dict for key, val in dict_val.iteritems(): AttributeError: 'dict' object has no attribute 'iteritems' Could it be something with the Python version? – Aktan A. May 20 '18 at 12:30
  • I just saw that iteritems() is now items() on Python 3. Edited it but not getting the desired result. Thanks anyway for the answer, I'm gonna keep trying. – Aktan A. May 20 '18 at 12:37
  • What result are you getting? – Subhrajyoti Das May 20 '18 at 12:43
  • Hello again. This is a gist with the code and result - https://gist.github.com/aktan4uk/b6f6f93d18d29d585099f1087bda065e – Aktan A. May 20 '18 at 12:58
  • Remove the print statement which prints key,value and try. I have updated the same above also. – Subhrajyoti Das May 20 '18 at 16:13
  • Thanks. Now it is {'level1_key1': '1', 'level2_key1': '2', 'level3_key1': 'Max depth'} Anyway, much appreciated! – Aktan A. May 20 '18 at 20:14
  • Can you mark my answer as the answer and close the question – Subhrajyoti Das May 21 '18 at 05:00
0

You can use dict.items in recursion:

d =  {u'level1_key2': {u'level2_key2': {u'level3_key1': u'Max depth'}, u'level2_key1': u'2'}, u'level1_key1': u'1'}
def flatten(d):
   _r = [[(a, b)] if not isinstance(b, dict) else flatten(b) for a, b in d.items()]
   return [i for b in _r for i in b]

new_d = dict(flatten(d))

Output:

{'level3_key1': 'Max depth', 'level2_key1': '2', 'level1_key1': '1'}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • Thanks for the answer. Unfortunately with this code I get the following: {'level1_key1': '1', 'level2_key1': '2', 'level3_key1': 'Congrats you have reached the maximum dept of the dict'} Probably it is something on my end I'm doing wrong... – Aktan A. May 20 '18 at 20:12