I have nested dictionaries:
{'key0': {'attrs': {'entity': 'p', 'hash': '34nj3h43b4n3', 'id': '4130'},
u'key1': {'attrs': {'entity': 'r',
'hash': '34njasd3h43b4n3',
'id': '4130-1'},
u'key2': {'attrs': {'entity': 'c',
'hash': '34njasd3h43bdsfsd4n3',
'id': '4130-1-1'}}},
u'key3': {'attrs': {'entity': 'r',
'hash': '34njasasasd3h43b4n3',
'id': '4130-2'},
u'key4': {'attrs': {'entity': 'c',
'hash': '34njawersd3h43bdsfsd4n3',
'id': '4130-2-1'}},
u'key5': {'attrs': {'entity': 'c',
'hash': '34njawersd3h43bdsfsd4n3',
'id': '4130-2-2'}}}},
'someohterthing': 'someothervalue',
'something': 'somevalue'}
given an id - one of all the ids like 4130 to 4130-2-2.
whats the easiest way to navigate to the correct dictionary?
Like if the given id is 4130-2-1 then it should reach the dictionary with key=key5
non xml approaches please.
Edit(1): The nesting is between 1 to 4 levels, but I know the nesting before I parse.
Edit(2): Fixed the code.
**Edit(3):**Fixed code again for string values of ids. Please excuse for the confusion created. This is final I hope :)
解决方案
Your structure is unpleasantly irregular. Here's a version with a Visitor function that traverses the attrs sub-dictionaries.
def walkDict( aDict, visitor, path=() ):
for k in aDict:
if k == 'attrs':
visitor( path, aDict[k] )
elif type(aDict[k]) != dict:
pass
else:
walkDict( aDict[k], visitor, path+(k,) )
def printMe( path, element ):
print path, element
def filterFor( path, element ):
if element['id'] == '4130-2-2':
print path, element
You'd use it like this.
walkDict( myDict, filterFor )
This can be turned into a generator instead of a Visitor; it would yield path, aDict[k] instead of invoking the visitor function.
You'd use it in a for loop.
for path, attrDict in walkDictIter( aDict ):
# process attrDict...