So I have this nested dictionary
myDictionary = {'x_1 = cloudy': {'x_0 = high': True, 'x_0 = low': False},
'x_1 = partly cloudy': False,
'x_1 = sunny': {'x_0 = high': False, 'x_0 = low': True}}
I have also a 2D array
X_test = np.array([['low', 'sunny'],['high', 'sunny'], ['high', 'cloudy'],
['low', 'partly cloudy'],['low', 'cloudy']])
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.
CodePudding user response:
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.