[PYTHON] Method to get all keys of nested dict

[^ 1]: Dr. shiracamus teaches us how to write more straightforwardly in the comments.

There is a smart way to write in the comments, so please refer to it.

test= {"w": {"y":{"z":1}},"ww":1, "www":{"yy":1}}

def allkeys(a):
    keys = a.keys()
    values = a.values()
    
    t = []
    for v in values:
        if isinstance(v, dict):
            t.extend(allkeys(v))
                
    result = [i for i in keys]
    result.extend(t)
    return result
    
r = allkeys(test)
print(r)


Execution result


['ww', 'www', 'w', 'yy', 'y', 'z']

https://gist.github.com/lnial/dedf2a98735c2826ca9ef7787bfb18fd


When the parent key is added to the key name

test= {"w": {"y":{"z":1}},"ww":1, "www":{"yy":1}}

def parentnema(k, v):
    return k +"."+ v

def allkeys(a):
    keys = a.keys()
    values = a.values()
    
    t = []
    for k in keys:
        v = a.get(k)
        if isinstance(v, dict):
            t.extend(map(lambda z: k + "." + z, allkeys(v)))

    result = [i for i in keys]
    result.extend(t)
    return result
    
r = allkeys(test)
print(r)

Execution result


 ['ww', 'www', 'w', 'www.yy', 'w.y', 'w.y.z']

https://gist.github.com/lnial/cd57861fb00a38537dda8974f96a1e1b

Recommended Posts

Method to get all keys of nested dict
List of shortcut keys dedicated to all yourself
How to get all the keys and values in the dictionary
I want to get the name of the function / method being executed
How to get rid of long comprehensions
Get all live tweets of professional baseball
4 ways to deal with missing dict keys
I want to get League of Legends data ③
I want to get League of Legends data ②
How to get dictionary type elements of Python 2.7
To get the path of the currently running python.exe
I want to get League of Legends data ①
Clustering of clustering method
How to get the number of digits in Python
Get to know the feelings of gradient boosting trees
Try to get the contents of Word with Golang
Script to get the expiration date of the SSL certificate
[Python] Get the number of views of all posted articles
[Python] I tried to get Json of squid ring 2
manage to get rid of heavy pyls in vim-lsp
I made a tool to get the answer links of OpenAI Gym all at once