Bando
Bando

Reputation: 1302

How can I check If there is a specified value in a dict?

I'm setting up a script, and I need to know If there is a specified value in my dictionary.

dict = {"1" : [1, 2, 3], "2" : [4, 5, 6]}

The fact is that I want to analyze all the lists from the dict values but I don't know how can I translate that.

How can I set a variable to True if 5 is in the dict?

Another topic where you can find a solution.

Upvotes: 0

Views: 54

Answers (3)

Hari Amoor
Hari Amoor

Reputation: 482

Doing this on my phone at 2:30am because I can't sleep, so bear with me for any bad formatting.

if any(5 in x for x in mydict.values()):
    print("dict analyzed")

That's one of the slick Pythonic ways of doing it. At a high level, you need to loop through mydict.values(), which provides an iterable of the values of mydict (dict is made up of key-value pairs.) If one of them contains 5, then print "dict analyzed."

The any function that I used is syntactic sugar; mind you, the high level idea remains the same.

Upvotes: 0

PyPingu
PyPingu

Reputation: 1747

Firstly, avoid assigning things to names of inbuilts like dict.

The following is specific to your use case:

mydict = {"1" : [1, 2, 3], "2" : [4, 5, 6]}
for key, vals in mydict.items():
    if 5 in vals:
        print('Dict analyzed')

Upvotes: -1

politinsa
politinsa

Reputation: 3720

for key, value in d.items():
    if 5 in value:
        print('5 in dict')
        break
  • Use break to stop the loop after finding the value and to save time not iterating over the whole dict.

Use iteritems() instead of items() if you are using python2.

Upvotes: 2

Related Questions