Searching Dictionaries
With both lists and strings, we used the in
and not in
operators to
search for specific values. These expressions returned either True
or
False
depending on if the value was found in the collection.
Example
|
|
Console Output
True
False
False
True
Since the elements in a dictionary come as pairs, we search for an item in either the set of keys or the set of values.
We practiced with the keys()
and values()
methods in the previous two
sections, and we can use them in a similar way to search a dictionary.
Example
|
|
Console Output
False
True
True
False
- In line 8,
101 in ticket_holders.keys()
returnsFalse
. Even though101
is in the dictionary, it is a value, and in this case we are searching through the keys. - In line 9,
101 in ticket_holders.values()
returnsTrue
. - In lines 11 and 12, we search for the string
'Jessi'
first in the keys and then in the values.
Default Search Method
If we do not add the keys()
or values()
method after the dictionary
name, Python searches the keys by default.
This means that
search_value in dictionary_name.keys()
returns the same result as
search_value in dictionary_name