This forum is now read-only. Please use our new forums! Go to forums

0 points
Submitted by uniric
over 11 years

How to look up if a certain value exists in a dictionary?

  1. How do you find out if a particular value exists in a dictionary?
    E.g. your_dictionary = {key2: value6, key5: value9, …}
    I want know if value77 exists in this dictionary.

  2. And what about when the values in a dictionary are lists?
    E.g. your_dictionary = {key2: [value21, value2, value43], key5: [value4, value15, value68], …}
    I want to know if value77 exists in this dictionary.

Answer 5072ad5a0538d0000206b5ab

1 vote

Permalink

  1. checking whether a value is in a dictionary:

    d = {"key1":"value1", "key2":"value2"}
    "value77" in d.values()  # ==> False
    
  2. checking whether a value is in one of the lists that are values of the dictionary: this is a bit harder, and can be done in several ways. One obvious way involves a loop (for every dictionary value, check if your item is in it), but the more “pythony” way would be to use a list comprehension:

    dic = {'key1': ["value1",  "value2"],
           'key2': ["value77", "something"] }
    "value77" in [x for v in dic.values() for x in v]
    

This will only work reliably if the dictionary only has lists as values. If it also had a string, such as 'hi', then the list [x for v in dic.values() for x in v] would contain the elements 'h' and 'i' but not "hi", so the query whether "hi" is inside the dictionary would come up False using the list comprehension above. To allow searching for single values as well as values inside lists, you can do something like this:

    dic = {'key1': ['value1', 'value2'],
           'key2':  'value77' }
    values = dic.values()
    'value77' in [x for v in values for x in v if type(v)==list] or 'value77' in values
    # ==> True
points
Submitted by Alex J
over 11 years

1 comments

uniric over 11 years

Thanks for your reply! Great help!