如果嵌套字典值中存在子字符串,是否返回父字典?

2024-05-14 20:13:08 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在嵌套的somedict中搜索子字符串“钢铁侠”后才返回“key\u three”。目标是如果找到"Iron man",则返回“key三”[key][dictionary having->;**]的所有父字典类型值,即including key_three_one:[values], key_three_two:[values]和第三个dictionary元素{}。你知道吗

somedict = [
               {
                  "anyKey":1,
                  "key_two":2,
                  **{            #key_three/value of key_three is nothing but a dictionary.
                    key_three_one: "spiderman",
                    key_three_two:"superman",
                    "key_three_three":{
                         "from_asguard" : "is not Iron Man:batman"
                    }
                  }**
    }]

我已经浏览了以下链接: 1Python return dictionary 2Iterate through a nested Dictionary and Sub Dictionary in Python 三。Loop through all nested dictionary values? 4Python function return dictionary?。你知道吗


Tags: key字符串dictionaryreturnisonenestedthree
1条回答
网友
1楼 · 发布于 2024-05-14 20:13:08

遍历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'}}}]

相关问题 更多 >

    热门问题