Nested dictionary to compare against 2D array

Viewed 51

So I have this nested dictionary

I am trying to test the array against the dictionary. The dictionary is essentially a trained decision tree such that:

  • high -> cloudy -> True (rain)
  • low -> sunny -> True (rain)

And any other condition means (no rain) For example, high -> partly cloudy -> False (no rain)

I wrote this function to get the desired output from the above but I am kind of failing at navigating the tree and getting wrong values.

def predict(x, d):
        for key, value in d.items():
            if type(value) is dict:
                if key.split(" = ")[1] in x:
                    return predict(x, value)
            else:
                return value
    
pred = [predict(x, tree) for x in X]

How can I navigate this dictionary and check for the above mentioned conditions? Appreciate the help.

1 Answers

i simplified the data a bit and the following works

def predict(x, d):                                                                                                   
    if type(d[x[1]]) is not dict:                                                                                    
        return d[x[1]]                                                                                               
    if x[1] in d.keys():                                                                                             
        return d[x[1]][x[0]]

I used in place of myDictionary

tree = {'cloudy': {'high': True, 'low': False},                                                                      
        'partly cloudy': False,                                                                                      
        'sunny': {'high': False, 'low': True}}

I assume that you get your code from some other example because i found complicated the recursion here. Thinking simple.

  • if you have a key which value is string return this
  • otherwise return the value of the nested dict.
Related