我有一本字典,如:
{
"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 和文件夹,它们是字典。
如果是文件夹,它必须有键'children',键的值是一个列表,我们可以在里面放更多的URL和文件夹。
现在我想遍历这个嵌套字典,获取所有子文件夹中的URL,所以我写了一个函数:
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 的字典,我不知道它在哪里。
我也想得到路径。我该怎么做?
最佳答案
不确定我是否得到了你想要的,但你可能想要这样做:
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
现在,您的函数会生成该项目和一系列键,以便在某个位置到达该项目。
关于python - 遍历嵌套字典并获取 Python 中的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11929904/