search

Home  >  Q&A  >  body text

Check if a given key already exists in the dictionary

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粉489081732P粉489081732419 days ago824

reply all(2)I'll reply

  • P粉674876385

    P粉6748763852023-10-09 00:56:30

    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.

    reply
    0
  • P粉914731066

    P粉9147310662023-10-09 00:33:49

    in Test whether the key exists in dict: < /p>

    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< /a> from the collections module:

    from collections import defaultdict
    
    d = defaultdict(int)
    
    for i in range(100):
        d[i % 10] += 1

    reply
    0
  • Cancelreply