遍历嵌套字典并获取 Python 中的路径? [英] Traverse a nested dictionary and get the path in Python?

查看:30
本文介绍了遍历嵌套字典并获取 Python 中的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本像这样的字典:

I have a dictionary like:

{
   "checksum": "b884cbfb1a6697fa9b9eea9cb2054183",
   "roots": {
      "bookmark_bar": {
         "children": [ {
            "date_added": "12989159740428363",
            "id": "4",
            "name": "test2",
            "type": "url",
            "url": "chrome://bookmarks/#1"
         } ],
         "date_added": "12989159700896551",
         "date_modified": "12989159740428363",
         "id": "1",
         "name": "bookmark_bar",
         "type": "folder"
      },
      "other": {
         "children": [ {
            "date_added": "12989159740428363",
            "id": "4",
            "name": "test",
            "type": "url",
            "url": "chrome://bookmarks/#1"
         } ],
         "date_added": "12989159700896557",
         "date_modified": "0",
         "id": "2",
         "name": "aaa",
         "type": "folder"
      },
      "synced": {
         "children": [  ],
         "date_added": "12989159700896558",
         "date_modified": "0",
         "id": "3",
         "name": "bbb",
         "type": "folder"
      }
   },
   "version": 1
}

一切从根"开始,它们有两种类型的数据:URL 和文件夹,它们是字典.如果是文件夹,它必须有key 'children',key的值是一个列表,我们可以在里面放更多的URL和文件夹.

Everything starts at 'roots', them there are two types of data: URL and folder, they are dictionaries. If it is a folder, it must have the key 'children', the value of the key is a list, we can put more URLs and folders in it.

现在我想遍历这个嵌套字典,获取所有子文件夹中的URL,所以我写了一个函数:

Now I want to traverse this nested dictionary, to get the URL in all sub-folder, so I wrote a function:

def traverse(dic):
    for i in dic:
        if i['type'] == 'folder':
            for j in traverse(i['children']):
                yield j
        elif i['type'] == 'url':
            yield i

我可以这样使用它:

traverse(dictionary['roots']['bookmark_bar']['children'])

它完美地工作.但它只是生成一个 URL 的字典,我不知道它在哪里.我也想得到路径.我该怎么做?

It works perfectly. But it just generate a dictionary of a URL, I don't know where is it. I want to get the path too. How can I do it?

推荐答案

不确定我是否得到了你想要的,但你可能想要这样做:

Not shure if I got what you want, but you might want to do this:

def traverse(dic, path=None):
    if not path:
        path = []
    for i in dic:
        local_path = path[:].append(i)
        if i['type'] == 'folder':
            for j in traverse(i['children'], local_path):
                yield j, local_path
        elif i['type'] == 'url':
            yield i, local_path

现在,您的函数会生成项目和一系列键,以到达特定位置的项目.

Now your function yields the item and a sequence of the keys to get to the item at a certain location.

这篇关于遍历嵌套字典并获取 Python 中的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆