How to Check If a Value Exists in a Dictionary

How to check if a value exists in a dictionary?

>>> d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
>>> 'one' in d.values()
True

Out of curiosity, some comparative timing:

>>> T(lambda : 'one' in d.itervalues()).repeat()
[0.28107285499572754, 0.29107213020324707, 0.27941107749938965]
>>> T(lambda : 'one' in d.values()).repeat()
[0.38303399085998535, 0.37257885932922363, 0.37096405029296875]
>>> T(lambda : 'one' in d.viewvalues()).repeat()
[0.32004380226135254, 0.31716084480285645, 0.3171098232269287]

EDIT: And in case you wonder why... the reason is that each of the above returns a different type of object, which may or may not be well suited for lookup operations:

>>> type(d.viewvalues())
<type 'dict_values'>
>>> type(d.values())
<type 'list'>
>>> type(d.itervalues())
<type 'dictionary-valueiterator'>

EDIT2: As per request in comments...

>>> T(lambda : 'four' in d.itervalues()).repeat()
[0.41178202629089355, 0.3959040641784668, 0.3970959186553955]
>>> T(lambda : 'four' in d.values()).repeat()
[0.4631338119506836, 0.43541407585144043, 0.4359898567199707]
>>> T(lambda : 'four' in d.viewvalues()).repeat()
[0.43414998054504395, 0.4213531017303467, 0.41684913635253906]

Check if a given key already exists in a dictionary

in tests for the existence of a key in a dict:

d = {"key1": 10, "key2": 23}

if "key1" in d:
print("this will execute")

if "nonexistent key" in d:
print("this will not")

Use dict.get() to provide a default value when the key does not exist:

d = {}

for i in range(10):
d[i] = d.get(i, 0) + 1

To provide a default value for every key, either use dict.setdefault() on each assignment:

d = {}

for i in range(10):
d[i] = d.setdefault(i, 0) + 1

or use defaultdict from the collections module:

from collections import defaultdict

d = defaultdict(int)

for i in range(10):
d[i] += 1

Check if value already exists within list of dictionaries and if it does update the counter

If you need your data to be in the format you show, and don't want to incur the cost of iterating over that list for every addition, that's not a problem. All you have to do is build an index for that data structure. The index will be a map with keys that are colors and values that are the index of that color in your original structure. You build this index first, and then you use it to process new entries efficiently. Here's how that goes:

colour_dict = [
{'main_colour': 'red', 'count': 1},
{'main_colour': 'blue', 'count': 5},
{'main_colour': 'green', 'count': 10},
]

colours = ["blue", "blue", "red", "greed", "red", "black"]

# Build an index mapping colors to positions in the 'colour_dict' list
index = {}
for i, entry in enumerate(colour_dict):
index[entry['main_colour']] = i

# Iterate over the new values, tallying them in the original structure, and
# adding new entries to both the original structure and the index when
# we discover colors that aren't yet in our structure. Note that there
# is just a single lookup per addition to the structure. No per-addition
# iteration here.
for colour in colours:
if colour in index:
colour_dict[index[colour]]['count'] += 1
else:
index[colour] = len(colour_dict)
colour_dict.append({'main_colour': colour, 'count': 1})

# Show the updated original structure
print(colour_dict)

Result:

[
{'main_colour': 'red', 'count': 3},
{'main_colour': 'blue', 'count': 7},
{'main_colour': 'green', 'count': 10},
{'main_colour': 'greed', 'count': 1},
{'main_colour': 'black', 'count': 1}
]

I am a teacher of programming, and I think this question is an opportunity to highlight an often overlooked technique. You don't have to change your existing data structure that isn't efficient to look things up in to be able to look things up in it efficiently. You can rather build an index into that structure that is efficient to look things up in that points back to the original structure for storage. This is a sort of "have your cake and eat it too" situation. It's worth grasping so you can have it in your bag of tricks.

This is like maintaining an index at the back of a book rather than restructuring the book's content to be easier to search for individual concepts at the cost of making it less valuable to read from front to back. A book index likewise gives you the best of both worlds.

Efficient way to check if dictionary key exists and has value

One approach would be to expect the failure and catch it:

try:
value = d['key2']['key3']
except (KeyError, TypeError):
pass

(don't call your variable the name of the type, it's a bad practice, I've renamed it d)

The KeyError catches a missing key, the TypeError catches trying to index something that's not a dict.

If you expect this failure to be very common, this may not be ideal, as there's a bit of overhead for a try .. except block.

In that case you're stuck with what you have, although I'd write it as:

if 'key2' in d and d['key2'] and 'key3' in d['key2']:
value = d['key2']['key3']

Or perhaps a bit more clearly:

if 'key2' in d and isinstance(d['key2'], dict) and 'key3' in d['key2']:
value = d['key2']['key3']

If you're about to assign something else to value in the else part (like None), you could also consider:

value = d['key2']['key3'] if 'key2' in d and d['key2'] and 'key3' in d['key2'] else None

how to check if a value exists in a dictionary of dictionaries in python?

You can go through the values and use an if condition:

for v in records.values():
pwd_secret = v.get('pwd_secret')
if pwd_secret == code:
# found

You don't really need to go through items because it looks like you don't need the key.

As for your error, ValueError is raised from the else branch because the pwd_secret doesn't equal code. If your not expecting this then you should set a breakpoint inside your editor and step through your code line by line to see what's actually happening.

Another easier debugging step is to just print out what each of these values are:

for v in records.values():
pwd_secret = v.get('pwd_secret')

print(f"pwd secret: {pwd_secret} and code: {code}") # print values here

if pwd_secret == code:
print("Secret is valid!")
else:
raise ValueError("code is invalid")

Which might also point out that v.get('pwd_secret') is giving you the default value None if 'pwd_secret' is not found in the inner dictionaries.

Additionally, if you want to check if any of the inner dictionaries have the code, you can use the built-in function any():

if any(v.get('pwd_secret') == code for v in records.values()):
print("Secret found!")
else:
raise ValueError("Secret not found")

Checking whether a key or value exists in a dictionary

Your problem is that 7 is a value, not a key. spam = {'name': 'Zophie', 'age':7} So if you do:

7 in spam >> False
'age' in spam >> True
7 in spam.values() >> True
7 in spam.keys() >> False

foo = {key0 : value0 , key1 : value1 ... keyN: valueN}

Take in to account, that in python the in looks for dictionary's keys list, not the values list. Unless you specify to do so.

check if a value exists in dictionary python

Use the hasattr method:

def attr(x, a):
return x.__getattribute__(a) if hasattr(x, a) else None

print k, attr(v, 'samplekey'), attr(v, 'units'), attr(v, 'comment')

Or alternatively, the getattr builtin (thanks RemcoGerlich!):

print k, getattr(v, 'samplekey', None)


Related Topics



Leave a reply



Submit