【问题标题】:Return a parent dictionary if substring inside a nested dictionary value exist?如果嵌套字典值中的子字符串存在,则返回父字典?
【发布时间】:2020-04-02 08:16:32
【问题描述】:

如何在嵌套的 somedict 中搜索子字符串“Iron Man”后返回“key_three”。目标是如果找到"Iron man",则返回“key_three”[key] [具有->** 的字典] 的所有父字典类型值,即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 return dictionary 2.Iterate through a nested Dictionary and Sub Dictionary in Python 3.Loop through all nested dictionary values? 4.Python function return dictionary?.

【问题讨论】:

  • 所以访问所有的链接,你肯定写了一些代码。您能否分享一下您的努力,看看您是否尝试自己找到解决方案。
  • code # n = len(somedict) x = 0 y = 0 # for x in range(n): # x +=1 for eachvalue in somedict[:][:]: x+=1 #print(eachvalue) for key,value in eachvalue[0].items(): #print(key,value) if 'Iron Man:' in str(value) : print(value) y+=1 print("\n\n\n", x) print("\n\n\n", y) IGNORE X and Y
  • 请不要将 cmets 用于代码。改为编辑您的问题。理想情况下,您的问题应该是独立的,因此包含回答您的问题所需的所有信息。

标签: python dictionary search substring


【解决方案1】:

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

【讨论】:

  • 这有帮助,但不是我所期望的,仍在寻找答案。
猜你喜欢
  • 2016-02-29
  • 1970-01-01
  • 2014-06-02
  • 2019-06-26
  • 2021-11-10
  • 2013-11-30
  • 2021-07-25
  • 1970-01-01
  • 2021-06-28
相关资源
最近更新 更多