apol96
apol96

Reputation: 210

Python - Check if a key exists in a large nested dictionary

So I have a large nested dictionary which has the following structure:

dic = {Review0: [{'there': 1, 'good': 3, 'news': 4, 'bad': 4, 'first': 3}], 
        Review1: [{'roomat': 1, 'recent': 1, 'bought': 1, 'explor': 1, 'sport': 1, 'suv': 2, 'realli': 3, 'nice': 4}],
        Review2: [{'found': 2, 'pregnanc': 2, 'also': 1, 'nice': 1, 'explor': 1, 'result': 2}]}

So in order to look at the keys in Review0, I can index through dictionary like this dic[0]

I want to find a way to loop through the nested dictionary to check if a key exists from Review0 to ReviewN, so for example if I want to look for the word pregnanc it will find it in Review2 and return True.

Any ideas?

Upvotes: 0

Views: 439

Answers (1)

bmjeon5957
bmjeon5957

Reputation: 291


def yourfunc(dic):
    for key, value in dic.items() :
        if 'pregnanc' in value[0] :
            return True


data = {'Review0': [{'there': 1, 'good': 3, 'news': 4, 'bad': 4, 'first': 3}], 
        'Review1': [{'roomat': 1, 'recent': 1, 'bought': 1, 'explor': 1, 'sport': 1, 'suv': 2, 'realli': 3, 'nice': 4}],
        'Review2': [{'found': 2, 'pregnanc': 2, 'also': 1, 'nice': 1, 'explor': 1, 'result': 2}]}



print (yourfunc(data))



or if your "reviews" might have multiple items :

def yourfunc(dic):
    for key, value in dic.items() :
        for item in value :
            if 'pregnanc' in item :
                return True

let me know if this isn't what you're looking for.

Upvotes: 2

Related Questions