0

## PYTHON 遞迴遍歷字典值與索引皆直接返回None

##########10/15更新後正確的####################

dic={
"AAAA":"5",
"GGGGG":{"F":"C4CC","R":"A66666"},
"BBBB":{"A":"CCCC","B":"666666"},
"XXXX":[],
"DDDD":"6"
}
def find_dic(dic,target,res=None):

for key ,values in dic.items():
if isinstance(values,dict):
res=find_dic(values,target)#更改的一行
#原本是return find_dic(dic[key],target)
if res:
return res
else:
if key==target:
res=values
return values
elif values==target:
res=key
return key

print(find_dic(dic,"XXXX"))

#################################################################

dic={
AAAA:"5",
XXXX:[],
DDDD:"6"
}
def find_dic(self,dic,target):
for key in dic.keys():
if isinstance(dic[key],dict):
return find_dic(dic[key],target)
else:
if key==target:
return dic[key]
elif dic[key]==target:
return key
print(find_dic(dic,"6"))
#這邊希望結果是找出6對應的key或者value是多少
正常情況應該印出"DDDD"

print(find_dic(dic,"AAA"))
印出"5" <==沒問題

dic={
AAAA:"5",
XXXX:[],
DDDD:"6"
}
def find_dic(self,dic,target):
for key in dic.keys():
if dic[key] is None or dic[key] == []:
print("GGG了")
if isinstance(dic[key],dict):
return find_dic(dic[key],target)
else:
if key==target:
return dic[key]
elif dic[key]==target:
return key
print(find_dic(dic,"6"))

key 不加 "" 能跑嗎

### 2 個回答

0
japhenchen
iT邦大師 1 級 ‧ 2020-10-15 07:34:32

dic = {
"AAAA":"5",
"GGGGG":{"F":"C4CC","R":"A66666"},
"BBBB":{"A":"CCCC","B":"666666"},
"XXXX":[],
"DDDD":"6"
}

print(list(filter(lambda elem: elem[1] == [], dic.items())))
print(list(filter(lambda elem: str(elem[1]) == "6", dic.items())))

1

dic = {
"AAAA": "5",
"GGGGG": {
"F": "C4CC",
"R": "A66666"
},
"BBBB": {
"A": "CCCC",
"B": "666666"
},
"XXXX": [],
"DDDD": "6"
}

def find(dic, target):
def dfs(key, val):
if key == target:
return ('key', val)
if val == target:
return ('val', key)
if isinstance(val, dict):
for k, v in val.items():
rlt = dfs(k, v)
if rlt:
return rlt
return dfs(None, dic)

print(find(dic,"XXXX"))   # ('key', [])