简体   繁体   中英

Get all the keys of a nested dict

With xmltodict I managed to get my code from xml in a dict and now I want to create an excel. In this excel the header of a value is going to be all the parents (keys in the dict). For example:

dict = {"name":"Pete", "last-name": "Pencil", "adres":{"street": "example1street", "number":"5", "roommate":{"gender":"male"}}}

The value male will have the header: adres/roommate/gender.

Here's a way to orgainze the data in the way your question asks:

d = {"name":"Pete", "last-name": "Pencil", "adres":{"street": "example1street", "number":"5", "roommate":{"gender":"male"}}}
print(d)
stack = [('', d)]
headerByValue = {}
while stack:
    name, top = stack.pop()
    if isinstance(top, dict):
        stack += (((name + '/' if name else '') + k, v) for k, v in top.items())
    else:
        headerByValue[name] = top

print(headerByValue)

Output:

{'adres/roommate/gender': 'male', 
'adres/number': '5', 
'adres/street': 'example1street', 
'last-name': 'Pencil', 
'name': 'Pete'}

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