全て、
私はPythonで辞書のリストの辞書を持っています。これは親子関係を表しています。子供を与えられたら、親を返したいと思います。
ここに私のコレクションがあります:
tree = { u'one' : [ { u'two' : [ { u'three' : [] }, { u'four' : [] } ] }, { u'five' : [ { u'six' : [] } ] } ] }
ご覧のとおり、"one" には子 "two" と "five" があり、"two" には子 "three" と "four" があり、"three" には子がありません。
次のコードは、特定の子の親を正しく処理します。
def find_parent(search_term,collection,parent=None):
if isinstance(collection,dict):
for key,value in collection.iteritems():
if key.lower() == search_term.lower():
print "the parent of %s is %s" % (key,parent)
return parent
if isinstance(value,list):
for v in value:
find_parent(search_term,v,key)
my_child = "two"
my_parent = find_parent(my_child,tree)
その関数の print ステートメントは、常に正しい値を出力します。しかし、my_parent にアクセスしようとすると、その値は常に "None" になります。ここで何かが範囲外になっているに違いありません。私はそれを修正する方法を理解できません。
ありがとう。