Check if a given key already exists in the dictionary
P粉489081732
P粉489081732 2023-10-08 11:38:59
0
2
612

I want to test whether the key exists in the dictionary before updating the value of the key. I wrote the following code:

if 'key1' in dict.keys():
  print "blah"
else:
  print "boo"

I don't think this is the best way to accomplish this task. Is there a better way to test keys in a dictionary?

P粉489081732
P粉489081732

reply all(2)
P粉674876385

Use key in my_dict directly instead of key in my_dict.keys():

if 'key1' in my_dict:
    print("blah")
else:
    print("boo")

This will be faster because it uses an O(1) hash of the dictionary instead of performing an O(n) linear search of the list of keys.

P粉914731066

in Test whether the key exists in dict:

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

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

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

Using dict.get() Provides a default value when the key does not exist:

d = {}

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

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

d = {}

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

...or better yet, use defaultdict from the collections module:

from collections import defaultdict

d = defaultdict(int)

for i in range(100):
    d[i % 10] += 1
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!