我有嵌套的字典:
{'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'}
给定一个id
-所有ids
中的一个,就像4130
to 4130-2-2
。
whats the easiest way to navigate to the correct dictionary?
例如,如果给定的id
是4130-2-1
,那么它应该使用key=key5
到达字典
请使用非xml方法。
编辑(1):嵌套在1
到4
级别之间,但我在解析之前知道嵌套。
编辑(2):修复代码。
**编辑(3):**重新修复ids
字符串值的代码。请原谅造成的混乱。这是我希望的最终结果:)
发布于 2008-12-19 12:45:29
你的结构不规则得令人不快。这是一个带有访问者函数的版本,它可以遍历attrs
子字典。
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
你会像这样使用它。
walkDict( myDict, filterFor )
可以将其转换为生成器,而不是访问者;它将yield path, aDict[k]
,而不是调用访问者函数。
您可以在for循环中使用它。
for path, attrDict in walkDictIter( aDict ):
# process attrDict...
发布于 2008-12-19 11:44:57
如果你想以一种通用的方式解决这个问题,不管你的字典中有多少层嵌套,那么创建一个遍历树的递归函数:
def traverse_tree(dictionary, id=None):
for key, value in dictionary.items():
if key == 'id':
if value == id:
print dictionary
else:
traverse_tree(value, id)
return
>>> traverse_tree({1: {'id': 2}, 2: {'id': 3}}, id=2)
{'id': 2}
发布于 2008-12-19 13:37:04
这类问题通常使用适当的类定义而不是通用字典来解决。
class ProperObject( object ):
"""A proper class definition for each "attr" dictionary."""
def __init__( self, path, attrDict ):
self.path= path
self.__dict__.update( attrDict )
def __str__( self ):
return "path %r, entity %r, hash %r, id %r" % (
self.path, self.entity, self.hash, self.id )
masterDict= {}
def builder( path, element ):
masterDict[path]= ProperObject( path, element )
# Use the Visitor to build ProperObjects for each "attr"
walkDict( myDict, builder )
# Now that we have a simple dictionary of Proper Objects, things are simple
for k,v in masterDict.items():
if v.id == '4130-2-2':
print v
此外,现在您有了正确的对象定义,可以执行以下操作
# Create an "index" of your ProperObjects
import collections
byId= collections.defaultdict(list)
for k in masterDict:
byId[masterDict[k].id].append( masterDict[k] )
# Look up a particular item in the index
print map( str, byId['4130-2-2'] )
https://stackoverflow.com/questions/380734
复制相似问题