简体   繁体   English

在嵌套Dict中递归查找路径

[英]Recursively finding paths in a nested Dict

I have a nested dictionary: 我有一个嵌套的字典:

d = {
 "@timestamp": "2019-01-08T19:33:50.066Z",
 "metricset": {
    "rtt": 2592,
    "name": "filesystem",
    "module": "system"
 },
 "system": {
    "filesystem": {
        "free_files": 9660022,
        "type": "rootfs",
        "device_name": "rootfs",
        "available": 13555355648,
        "files": 9766912,
        "mount_point": "/",
        "total": 19992150016,
        "used": {
            "pct": 0.322,
            "bytes": 6436794368
        },
        "free": 13555355648
    }
 },
 "host": {
    "name": "AA"
 },
 "beat": {
    "name": "AA",
    "hostname": "AA",
    "version": "6.3.2"
  }
}

What I would like to do is write this dictionary to a CSV file. 我想做的就是将此字典写入CSV文件。 I'd like the headers of the csv to be something like this: 我希望csv的标头是这样的:

system.filesystem.type

where the path is made up by each level separated by a period. 其中的路径由每个级别(由句点分隔)组成。 I am able to go through the dictionary and get most of the headers I need; 我能够浏览字典并获得所需的大多数标题。 however my problem is with duplicate values. 但是我的问题是重复的值。

PROBLEM: I recursively go through the dict and grab all the values and put them in a list. 问题:我递归地检查字典并获取所有值并将它们放在列表中。 Then, I am searching for those values in the dictionary again, but this time saving the path to construct the header. 然后,我再次在字典中搜索这些值,但是这次保存了构造标头的路径。 However, with duplicate values (ie the value "rootfs"), I am getting only the first key-value ("type": "rootfs") returned. 但是,使用重复的值(即值“ rootfs”),我只得到返回的第一个键值(“ type”:“ rootfs”)。

Here is my traversal to grab all the values from the dict, which does exactly what I want: 这是我从dict中获取所有值的遍历,这正是我想要的:

def traverse(valuelist, dictionary):

    for k,v in dictionary.items():

       if isinstance(v, dict):
         traverse(valuelist,v)
       else:
         valuelist.append(v)

    return valuelist

Now here is the code that grabs the path for each value from the code above: 现在,这里是从上面的代码中获取每个值的路径的代码:

def getpath(nested_dict, value, prepath=()):
    for k,v in nested_dict.items():
        path = prepath + (k,)
        if v == value: # found value
           return path
        elif hasattr(v, 'items'): # v is a dict
            p = getpath(v, value, path) # recursive call
            if p is not None:
                return p

This part is not my own code. 这部分不是我自己的代码。 I found it here on SO and would like to modify it to grab every unique path for duplicate values (ie For value "rootfs" 1st path: "system.filesystem.type" 2nd path: "system.filesystem.device_name"). 我在SO上找到了它,并想对其进行修改以获取重复值的每个唯一路径(例如,对于值“ rootfs”,第一路径:“ system.filesystem.type”,第二路径:“ system.filesystem.device_name”)。

Thank you very much, and any help is appreciated! 非常感谢,感谢您的帮助!

An easy way to do this is to turn getpath into a generator: 一种简单的方法是将getpath转换为生成器:

def getpath(nested_dict, value, prepath=()):
    for k,v in nested_dict.items():
        path = prepath + (k,)
        if v == value: # found value
            yield path # yield the value
        elif hasattr(v, 'items'):
            yield from getpath(v, value, path) # yield all paths from recursive call

This way it yields every single valid path recursively. 这样,它递归地yields每个有效路径。 You can use it like so: 您可以这样使用它:

for path in getpath(nested_dict, value):
    # do stuff with path

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

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