如何返回“ key_three”,仅在嵌套somedict中搜索子字符串“ Iron Man”之后。目的是如果找到“钢铁侠”,则返回整个父词典类型值“ key_three” [key]。
somedict = [
{
"anyKey":1,
"key_two":2,
"key_three":{
"inside_key_three":{
"from_asguard" : "is not Iron Man"
}
}
}]
我已经通过以下链接进行了操作:1.Python return dictionary2.Iterate through a nested Dictionary and Sub Dictionary in Python3.Loop through all nested dictionary values?4. Python function return dictionary?。
反复浏览somedict
列表中词典的各项,
for key,value in somedict[0].items():
if 'Iron Man' in str(value):
print(key, value)
>>>key_three {'inside_key_three': {'from_asguard': 'is not Iron Man'}}
或者您可以使用列表理解:
[{k:v} for k,v in somedict[0].items() if 'Iron Man' in str(v)]
>>>[{'key_three': {'inside_key_three': {'from_asguard': 'is not Iron Man'}}}]