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?

10
  • 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. Commented May 9, 2018 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. Commented May 9, 2018 at 17:01
  • 1
    You can use a try and except KeyError block to handle missing keys Commented May 9, 2018 at 17:02
  • @eyllanesc: The question you marked as original has the keys at the same depth, this question has nested keys Commented May 9, 2018 at 17:10
  • @Andomar I fixed it, I added the new duplicate: stackoverflow.com/questions/14962485/… Commented May 9, 2018 at 17:14

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.