简体   繁体   中英

Printing key values of multi level dictionary in python

I have following data:-

data={
    "a":{
        "b":{
            "c":1
            },
            "f":5
        },
    "d":"2",
    "e":"3",
    "g":{
        "h":{
            "j":"10"
            }
        }
    }

I tried and currently I have following code:-

def myprint(d):
    for k, v in d.iteritems():
        if isinstance(v, dict):
            print "{0}".format(k, v)
            myprint(v)
    else:
        print "{0} : {1}".format(k, v)

   myprint(data)

The above code prints following:-

a
b
c : 1
f : 5
e : 3
d : 2
g
h
j : 10

I wanted the output to be following:-

a__b__c = 1
a__f = 5
d = 2
e = 3
g__h__j = 10

Following is the IDE link: https://ideone.com/hWlYUM

Pass along a prefix for recursive calls:

def print_nested(d, prefix=''):
    for k, v in d.items():
        if isinstance(v, dict):
            print_nested(v, '{}{}_'.format(prefix, k))
        else:
            print '{}{} = {}'.format(prefix, k, v)

Demo:

>>> print_nested(data)
a_b_c = 1
a_f = 5
e = 3
d = 2
g_h_j = 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM