簡體   English   中英

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

[英]Return a parent dictionary if substring inside a nested dictionary value exist?

如何僅在嵌套的 somedict 中搜索子字符串“Iron Man”后返回“key_three”。 目標是如果找到"Iron man"則返回“key_three” [key] [dictionary including key_three_one:[values], key_three_two:[values] ->** ] 的所有父字典類型值,即including key_three_one:[values], key_three_two:[values]和第三個字典元素{}

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"
                    }
                  }**
    }]

我已經瀏覽過這些鏈接: 1. Python 返回字典2. 在 Python 中遍歷嵌套字典和子字典3. 循環遍歷所有嵌套字典值? 4. Python函數返回字典? .

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM