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

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

Usekey in my_dictdirectly instead ofkey in my_dict.keys():

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

This willbe fasterbecause it uses an O(1) hash of the dictionary instead of performing an O(n) linear search of the list of keys.

    P粉914731066

    inTest whether the key exists indict:

    d = {"key1": 10, "key2": 23} if "key1" in d: print("this will execute") if "nonexistent key" in d: print("this will not")

    Usingdict.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 foreachkey, usedict.setdefault()on each job:

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

    ...or better yet, usedefaultdictfrom thecollectionsmodule:

    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!