如何在带有列表的嵌套字典中查找键的值?
How to find a value of a key in a nested dictionary with lists?
我需要解析一些非常奇怪的 json 有效载荷,但我完全卡住了..
假设我有一个嵌套字典,其中的列表如下所示:
test_dict1 = {
"blah":"blah",
"alerts": [{"test1":"1", "test":"2"}],
"foo": {
"foo":"bar",
"foo1": [{"test3":"3"}]
}}
是否有一个函数可以为我提供键 test3
的值?或者更确切地说,键 test3
第一次出现的第一个值
编辑
我的意思是一个可以搜索key test3的函数,因为我主要关心的是key,而且我能得到的不同字典可能有不同的结构
就像访问任何其他嵌套结构一样访问它:
test_dict1["foo"]["foo1"][0]["test3"]
另外,第一次出现是什么意思?字典没有特定的顺序,所以这对你来说真的没什么用。
如果您只想要 test3 的值,那么您可以通过以下方式获得它,
test_dict1["foo"]["foo1"][0]["test3"]
但是,如果您想要动态地获取值,那么它将使用不同的方法来完成。
你看,你可以在使用字典时使用键名,在列表中使用索引。
由于您不知道 if 值的内部有多深,建议使用递归函数遍历所有层直到找到它。我在下面使用了 DFS。
def search(ld, find):
if(type(ld)==list):
for i in ld:
if(type(i)==list or type(i)==dict):
result=search(i, find)
if(result!=None): return result
elif(type(ld)==dict):
try:
return ld[find]
except(KeyError):
for i in ld:
if(type(ld[i])==list or type(ld[i])):
result=search(ld[i], find)
if(result!=None): return result
else:
return None
test_dict1 = {
"blah":"blah",
"alerts": [{"test1":"1", "test":"2"}],
"foo": {
"foo":"bar",
"foo1": [{"test3":"3"}]
}}
print(search(test_dict1, "test3"))
我需要解析一些非常奇怪的 json 有效载荷,但我完全卡住了..
假设我有一个嵌套字典,其中的列表如下所示:
test_dict1 = {
"blah":"blah",
"alerts": [{"test1":"1", "test":"2"}],
"foo": {
"foo":"bar",
"foo1": [{"test3":"3"}]
}}
是否有一个函数可以为我提供键 test3
的值?或者更确切地说,键 test3
编辑 我的意思是一个可以搜索key test3的函数,因为我主要关心的是key,而且我能得到的不同字典可能有不同的结构
就像访问任何其他嵌套结构一样访问它:
test_dict1["foo"]["foo1"][0]["test3"]
另外,第一次出现是什么意思?字典没有特定的顺序,所以这对你来说真的没什么用。
如果您只想要 test3 的值,那么您可以通过以下方式获得它,
test_dict1["foo"]["foo1"][0]["test3"]
但是,如果您想要动态地获取值,那么它将使用不同的方法来完成。 你看,你可以在使用字典时使用键名,在列表中使用索引。
由于您不知道 if 值的内部有多深,建议使用递归函数遍历所有层直到找到它。我在下面使用了 DFS。
def search(ld, find):
if(type(ld)==list):
for i in ld:
if(type(i)==list or type(i)==dict):
result=search(i, find)
if(result!=None): return result
elif(type(ld)==dict):
try:
return ld[find]
except(KeyError):
for i in ld:
if(type(ld[i])==list or type(ld[i])):
result=search(ld[i], find)
if(result!=None): return result
else:
return None
test_dict1 = {
"blah":"blah",
"alerts": [{"test1":"1", "test":"2"}],
"foo": {
"foo":"bar",
"foo1": [{"test3":"3"}]
}}
print(search(test_dict1, "test3"))