如果嵌套字典值内的子字符串存在,返回父字典?

问题描述 投票:0回答:1

如何返回“ 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?

python dictionary search substring
1个回答
0
投票

反复浏览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'}}}]
© www.soinside.com 2019 - 2024. All rights reserved.