![](/img/trans.png)
[英]Python recursive function to match key values and return path in nested dictionary
[英]Print complete key path for all the values of a python nested dictionary
如果下面是我的嵌套字典,我想通過遞歸方式解析並打印所有值以及嵌套鍵的完整路徑。
my_dict = {'attr':{'types':{'tag':{'name':'Tom', 'gender':'male'},'category':'employee'}}}
預期產量:
Key structure : my_dict["attr"]["types"]["tag"]["name"]<br>
value : "Tom"<br>
Key structure : my_dict["attr"]["types"]["tag"]["gender"]<br>
value : "male"<br>
Key structure : my_dict["attr"]["types"]["category"]<br>
value : "employee"<br>
我寫了一個遞歸函數,但運行到這個:
my_dict = {'attr':{'types':{'tag':{'name':'Tom','gender':'male'},'category':'employee'}}}
def dict_path(path,my_dict):
for k,v in my_dict.iteritems():
if isinstance(v,dict):
path=path+"_"+k
dict_path(path,v)
else:
path=path+"_"+k
print path,"=>",v
return
dict_path("",my_dict)
輸出:
_attr_types_category =>員工
_attr_types_category_tag_gender =>男
_attr_types_category_tag_gender_name =>湯姆
在上面:對於男性,關鍵結構不應該包含“類別”如何保留正確的關鍵結構?
你不應該改變dict_path()
函數中的path
變量:
def dict_path(path,my_dict):
for k,v in my_dict.iteritems():
if isinstance(v,dict):
dict_path(path+"_"+k,v)
else:
print path+"_"+k,"=>",v
dict_path("",my_dict)
正如catavaran所提到的,你的問題是由你的for
循環中的path
變量添加新的路徑組件引起的。 您需要將新路徑放入調用中,以便將其傳遞到下一級遞歸,並且不會干擾當前遞歸級別的for
循環中后續項的路徑。
這是一個使用遞歸生成器的替代解決方案,而不是在dict_path
函數內打印結果。 (FWIW,我使用print json.dumps(my_dict, indent=4)
重新格式化字典)。
my_dict = {
"attr": {
"types": {
"category": "employee",
"tag": {
"gender": "male",
"name": "Tom"
}
}
}
}
def dict_path(my_dict, path=None):
if path is None:
path = []
for k,v in my_dict.iteritems():
newpath = path + [k]
if isinstance(v, dict):
for u in dict_path(v, newpath):
yield u
else:
yield newpath, v
for path, v in dict_path(my_dict):
print '_'.join(path), "=>", v
產量
attr_types_category => employee
attr_types_tag_gender => male
attr_types_tag_name => Tom
我建議你使用python-benedict
,一個固定的python dict子類,具有完整的keypath支持和許多實用方法。
你只需要施放現有的dict:
my_dict = benedict(my_dict)
現在您的dict具有完整的keypath支持,您可以輕松獲取dict中所有keypath的列表:
print(my_dict.get_keypaths())
這里是庫存儲庫和文檔: https : //github.com/fabiocaccamo/python-benedict
只需添加上面的@catavaran代碼。 如果dict
值是list
,並且list
可能有dict
或值本身,那么這段代碼可能有所幫助。 我剛剛將分隔符修改為點。
def dict_path(path,my_dict):
for k,v in my_dict.iteritems():
if isinstance(v,list):
for i, item in enumerate(v):
dict_path( path + "." + k + "." + str(i), item)
elif isinstance(v,dict):
dict_path(path+"."+k,v)
else:
print path+"."+k, "=>", v
謝謝@catavaran
,您的代碼幫助了我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.