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

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

问题描述

我有一个像这样的字典

{
   "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
}

一切都始于"roots",它们有两种类型的数据:URL和文件夹,它们是字典. 如果它是文件夹,则必须具有键"children",该键的值是一个列表,我们可以在其中放置更多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天全站免登陆