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
}
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.
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
and I can use it like that:
traverse(dictionary['roots']['bookmark_bar']['children'])
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.