0

For the following definition of a dict:

data={
'key_1':1,
'key_2':2,
'key_3':[
    {
        'key_4':[4,5],
        'key_5':[6,7],
        'key_6':8
    },
    {
        'key_4':[9,10],
        'key_5':[11,12],
        'key_6':13
    }
],
'key_7':14
}

I basically need to check whether a given key exists in data or not and if it does, the values associated with the key must be printed.

Example:

input: key_5
output: ([6,7],[11,12])

input: key_8
output: DNE

Code that I wrote:

key = input()
def find_key(data,key):
    if key in data:
        print(data[key])
        return

    for k, v in data.items():
            if isinstance(v,list):
                for x in v:
                    if isinstance(x,dict) and find_key(x,key) is not None:
                        print(find_key(x,key))

find_key(data,key)

I'm not sure about where to place the condition of 'DNE' in this code. Can I get some help on this?

Sricharan
  • 11
  • 4
  • 2
    You probably want to use recursion to access nested dictionaries here. There are plenty of questions on SO that discuss how to do this. – user3483203 May 09 '18 at 16:59
  • 1
    Maybe reconsider how you are building the dict in the first place, so that the values are already lists of lists (or lists of references to lists, to avoid duplication). Single items can be lists of length 1. – Benjamin May 09 '18 at 17:01
  • 1
    You can use a *try* and *except KeyError* block to handle missing keys – ma3oun May 09 '18 at 17:02
  • @eyllanesc: The question you marked as original has the keys at the same depth, this question has nested keys – Andomar May 09 '18 at 17:10
  • @Andomar I fixed it, I added the new duplicate: https://stackoverflow.com/questions/14962485/finding-a-key-recursively-in-a-dictionary – eyllanesc May 09 '18 at 17:14
  • @eyllanesc: Your new suggested original doesn't have arrays in its dictionary. So the accepted answer's `if isinstance(v,dict):` means it won't work for this question, and it's not an exact duplicate either – Andomar May 09 '18 at 17:18
  • @Andomar With the combination of both questions you get the logic of finding the key, if you think it is not duplicated I invite you to reopen it, the community will decide. :D – eyllanesc May 09 '18 at 17:21
  • @eyllanesc: Why would you vote to close a question if you cannot find an exact duplicate? – Andomar May 09 '18 at 17:22
  • This code may be of help: https://repl.it/@SteamLOLed/ThornyWobblyMicrokernel – francisco sollima May 09 '18 at 17:34
  • I changed my mind; the other question is not a duplicate - the question of how to search dictionaries recursively needs an appropriate how-to canonical, which is separate from the question of what was wrong with *that particular attempt*. – Karl Knechtel Aug 08 '22 at 00:42

1 Answers1

0

And what about this? It's a simple recursion...

from sys import exit


def check(d, key): # d means dictionary
    for k in d:
        if k == key:
            print(d[key])
        elif (type(d[k]) == list):
            for e in d[k]:
                if (type(e) == dict):
                    check(e, key)