0

How to return "key_three" Only after searching for a substring "Iron Man" inside the nested somedict. The objective is if "Iron man" is found return all of the entire parent dictionary type value of "key_three" [key] [dictionary having ->** ] i.e. including key_three_one:[values], key_three_two:[values] and the third dictionary-element {}.

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

I have already gone through these links : 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?.

s dev
  • 1
  • 1
  • 4
    So visiting all the links, you must have written some code. Can you please share your efforts, to see that you tried to come to a solution on your own. – AnsFourtyTwo Dec 09 '19 at 08:53
  • `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 – s dev Dec 09 '19 at 12:23
  • Do not use comments for code, please. Edit your question instead. Ideally, your question should be self-contained, thus contain all the required information to answer your question. – AnsFourtyTwo Dec 09 '19 at 15:53

1 Answers1

0

iterate through items of the dictionary inside your somedict list,

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'}}

or you can use list comprehension:

[{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'}}}]
Shijith
  • 4,602
  • 2
  • 20
  • 34