This forum is now read-only. Please use our new forums! Go to forums
How to look up if a certain value exists in a dictionary?
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.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
checking whether a value is in a dictionary:
d = {"key1":"value1", "key2":"value2"} "value77" in d.values() # ==> False
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
Popular free courses
- Free Course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner friendly,4 LessonsLanguage Fluency - Free Course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner friendly,11 LessonsLanguage Fluency - Free Course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner friendly,6 LessonsLanguage Fluency
1 comments
Thanks for your reply! Great help!