擅长:python、mysql、java
<p>使用正确的类定义(而不是泛型字典)通常可以更好地解决此类问题。</p>
<pre><code>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
</code></pre>
<p>另外,既然已经有了正确的对象定义,可以执行以下操作</p>
<pre><code># 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'] )
</code></pre>