0

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.

Bando
  • 1,223
  • 1
  • 12
  • 31
  • Possible duplicate of [Get key by value in dictionary](https://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary) – Cray Jun 24 '19 at 10:21

3 Answers3

2
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.

politinsa
  • 3,480
  • 1
  • 11
  • 36
0

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.

Hari Amoor
  • 442
  • 2
  • 7
-1

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')
PyPingu
  • 1,697
  • 1
  • 8
  • 21