I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code:
JavaScript
x
5
1
if 'key1' in dict.keys():
2
print "blah"
3
else:
4
print "boo"
5
I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?
Advertisement
Answer
in
tests for the existence of a key in a dict
:
JavaScript
1
8
1
d = {"key1": 10, "key2": 23}
2
3
if "key1" in d:
4
print("this will execute")
5
6
if "nonexistent key" in d:
7
print("this will not")
8
Use dict.get()
to provide a default value when the key does not exist:
JavaScript
1
5
1
d = {}
2
3
for i in range(10):
4
d[i] = d.get(i, 0) + 1
5
To provide a default value for every key, either use dict.setdefault()
on each assignment:
JavaScript
1
5
1
d = {}
2
3
for i in range(10):
4
d[i] = d.setdefault(i, 0) + 1
5
or use defaultdict
from the collections
module:
JavaScript
1
7
1
from collections import defaultdict
2
3
d = defaultdict(int)
4
5
for i in range(10):
6
d[i] += 1
7