JV.*_*JV. 10 python parsing struct dictionary nested
我有嵌套字典:
{'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'}
Run Code Online (Sandbox Code Playgroud)
给予id - 一个ids喜欢4130的4130-2-2.
导航到正确字典的最简单方法是什么?
就像给定id的4130-2-1那样它应该到达字典key=key5
非xml方法请.
编辑(1):筑巢之间1到4的水平,但我知道我的嵌套前解析.
编辑(2):修复了代码.
**编辑(3):**再次固定代码的字符串值ids.请原谅造成的混乱.这是最后我希望:)
S.L*_*ott 15
你的结构令人不快不规律.这是一个带有访问者功能的版本,可以遍历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
Run Code Online (Sandbox Code Playgroud)
你会像这样使用它.
walkDict( myDict, filterFor )
Run Code Online (Sandbox Code Playgroud)
这可以变成发电机而不是访客 ; 它不会yield path, aDict[k]调用访问者功能.
你可以在for循环中使用它.
for path, attrDict in walkDictIter( aDict ):
# process attrDict...
Run Code Online (Sandbox Code Playgroud)
Map*_*pad 13
如果你想以一般方式解决问题,无论你在dict中有多少级别的嵌套,那么创建一个遍历树的递归函数:
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}
Run Code Online (Sandbox Code Playgroud)
这种问题通常可以通过适当的类定义来解决,而不是通用的字典.
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
Run Code Online (Sandbox Code Playgroud)
此外,既然您有正确的对象定义,您可以执行以下操作
# 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'] )
Run Code Online (Sandbox Code Playgroud)
小智 5
这是一个老问题,但仍然是google的最高结果,所以我会更新:
一位朋友和我自己发布了一个库来解决(非常接近)这个确切的问题.dpath-python(与执行类似操作的perl dpath模块无关).
http://github.com/akesterson/dpath-python
您需要做的就是这样:
$ easy_install dpath
>>> import dpath.util
>>> results = []
>>> for (path, value) in dpath.util.search(my_dictionary, "*/attrs/entity/4130*", yielded=True):
>>> ... parent = dpath.util.search("/".join(path.split("/")[:-2])
>>> ... results.append(parent)
Run Code Online (Sandbox Code Playgroud)
...这将为您提供与您的搜索匹配的所有字典对象的列表,即具有(key = 4130*)的所有对象.父位有点笨拙,但它会起作用.