Using "if in" with a dictionary

I can't believe it, but I was puzzled by what should be a very simple task.

I need to check if a value is in a dictionary like either a key or a value. I can find the keys using if 'A' in dictionary, however I cannot get this to work for values. I understand that I can use the for loop for this, and I can resort to this, but I was wondering if there is a built-in method for it.

+4
source share
4 answers

You can use the operator inand anylike this

value in dictionary or any(value in dictionary[key] for key in dictionary)

value in dictionary , Truthy, value dictionary

any(value in dictionary[key] for key in dictionary)

, value .

: ,

  • any , .

, , in ==

value in dictionary or any(value == dictionary[key] for key in dictionary)

DSM, value in dict.itervalues() Python 2.x, value in dict.values() Python 3.x

+9

:

my_keys = my_dict.keys()

my_keys - ,

my_values = my_dict.values()

if some_thing in my_keys
if some_thing in my_values

, ,

if some_thing in my_dict
+3

, d.values()

d.keys() - dict ( , , )

d.values() - dict. ( .)

d - dict

:

d.items() 

(key, value) dict

:

[(key, value), (key, value) ... ]

, d.keys() d.values() in

d.items() :

for pair in d.items():
    if "A" in pair:
        do your thing

d.iteritems(), for, google.

+3

: .. keys values in, , :

dict = {"a" : "b", "c" : "d"}

value = "b"

if value in dict.keys() + dict.values():
    print "present"
else: 
    print "absent"

You can optimize this further to use the built- O(1)in key check (from the @Wooble comment) and search for dictionary values ​​only if it is not in the keys

if value in dict or value in dict.values():
    print "present"

`

+3
source

Source: https://habr.com/ru/post/1534126/


All Articles