简体   繁体   English

获取嵌套字典的所有键

[英]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.使用 xmltodict 我设法从 dict 中的 xml 获取我的代码,现在我想创建一个 excel。 In this excel the header of a value is going to be all the parents (keys in the dict).在这个excel中,一个值的标题将是所有的父母(字典中的键)。 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.值男性将有标题: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'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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