简体   繁体   中英

How to get the level of values in a specific key in nested Dictionary

Assuming that I have the following dictionary:

a={'brother': {'name': 'paskal', 'surname': 'leonis'},
   'family':  {'parents': {'father': 'telis',
                           'mother': 'xrisanthi',
                           'name': 'dimitris'}},
   'name': 'alekos'}

And the desired output is to get a list:

[['paskal',1],['dimitris',2],['alekos',0]]

So what I want is to get the values of all the keys that have the name with the level that they key was found(starting with zero)

Until now I have succesufully got the values but the levels that I found are incorrect. I am using the following code:

from six import iteritems
def findKey_printValue(key, document,c=0):
    if isinstance(document, dict):
        for k, v in iteritems(document):
            if k == key:
                yield [v,c]
            elif isinstance(v, dict):
                c+=1
                for result in findKey_printValue(key, v,c):
                    yield result


In [125]:list(findKey_printValue('name',a))
Out[125]:[['dimitris', 2], ['paskal', 2], ['alekos', 2]]

Any help?

Don't update the value of c in the current function itself, just do it in the call to the recursion:

    elif isinstance(v, dict):
        for result in findKey_printValue(key, v, c+1):
            yield result

Do not pass c , but the increment of the value (else all your results have a reference to c ):

from six import iteritems
def findKey_printValue(key, document,c=0):
    if isinstance(document, dict):
        for k, v in iteritems(document):
            if k == key:
                yield (v,c)
            elif isinstance(v, dict):
                for result in findKey_printValue(key, v, c + 1):
                    yield result

You need to make sure the c variable only increases as you go down a level. When you run back up the stack, c should not have changed.

Modify this :

   c+=1
   for result in findKey_printValue(key, v,c):
       yield result

to this:

   for result in findKey_printValue(key, v,c+1):
       yield result


a={'brother': {'name': 'paskal', 'surname': 'leonis'},
   'family':  {'parents': {'father': 'telis',
                           'mother': 'xrisanthi',
                           'name': 'dimitris'}},
   'name': 'alekos'}

holder = {}

def get(d, count):
    if isinstance(d, dict):
        for key, val in d.items():
            if isinstance(val, dict):
                get(val, count+1)
            elif key=='name':
                holder[val]=count

get(a, 0)

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