检查给定的键是否已经存在于字典中

I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code:

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

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?

转载于:https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary

in is the intended way to test for the existence of a key in a dict.

d = dict()

for i in xrange(100):
    key = i % 10
    if key in d:
        d[key] += 1
    else:
        d[key] = 1

If you wanted a default, you can always use dict.get():

d = dict()

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

... and if you wanted to always ensure a default value for any key you can use defaultdict from the collections module, like so:

from collections import defaultdict

d = defaultdict(lambda: 0)

for i in xrange(100):
    d[i % 10] += 1

... but in general, the in keyword is the best way to do it.

You don't have to call keys:

if 'key1' in dict:
  print "blah"
else:
  print "boo"

That will be much faster as it uses the dictionary's hashing as opposed to doing a linear search, which calling keys would do.

You can shorten this:

if 'key1' in dict:
    ...

However, this is at best a cosmetic improvement. Why do you believe this is not the best way?

I would recommend using the setdefault method instead. It sounds like it will do everything you want.

>>> d = {'foo':'bar'}
>>> q = d.setdefault('foo','baz') #Do not override the existing key
>>> print q #The value takes what was originally in the dictionary
bar
>>> print d
{'foo': 'bar'}
>>> r = d.setdefault('baz',18) #baz was never in the dictionary
>>> print r #Now r has the value supplied above
18
>>> print d #The dictionary's been updated
{'foo': 'bar', 'baz': 18}

You can test for the presence of a key in a dictionary, using the in keyword:

d = {'a': 1, 'b': 2}
'a' in d # <== evaluates to True
'c' in d # <== evaluates to False

A common use for checking the existence of a key in a dictionary before mutating it is to default-initialize the value (e.g. if your values are lists, for example, and you want to ensure that there is an empty list to which you can append when inserting the first value for a key). In cases such as those, you may find the collections.defaultdict() type to be of interest.

In older code, you may also find some uses of has_key(), a deprecated method for checking the existence of keys in dictionaries (just use key_name in dict_name, instead).

You can use the has_key() method:

if dict.has_key('xyz')==1:
    #update the value for the key
else:
    pass

Or the dict.get method to set a default value if not found:

mydict = {"a": 5}

print mydict["a"]            #prints 5
print mydict["b"]            #Throws KeyError: 'b'

print mydict.get("a", 0)     #prints 5
print mydict.get("b", 0)     #prints 0

Just an FYI adding to Chris. B (best answer):

d = defaultdict(int)

Works as well; the reason is that calling int() returns 0 which is what defaultdict does behind the scenes (when constructing a dictionary), hence the name "Factory Function" in the documentation.

What about using EAFP (easier to ask forgiveness than permission):

try:
   blah = dict["mykey"]
   # key exists in dict
except KeyError:
   # key doesn't exist in dict

See other SO posts:

Using try vs if in python or

Checking for member existence in Python

For additional info on speed execution of the accepted answer's proposed methods (10m loops):

  • 'key' in mydict elapsed time 1.07 sec
  • mydict.get('key') elapsed time 1.84 sec
  • mydefaultdict['key'] elapsed time 1.07 sec

Therefore using in or defaultdict are recommended against get.

print dict.get('key1', 'blah')

Won't print boo for the values in the dict, but accomplishes the goal by printing the value of key1 to confirm it's existence instead.

For checking you can use has_key() method

if dict.has_key('key1'):
   print "it is there"

If you want a value then you can use get() method

a = dict.get('key1', expeced_type)

If you want a tuple or list or dictionary or any string as a default value as return value, then use get() method

a = dict.get('key1', {}).get('key2', [])

Easiest one is if you know which key(key name) is to look for:

# suppose your dictionary is
my_dict = {'foo': 1, 'bar': 2}
# check if a key is there
if 'key' in my_dict.keys():   # it will evaluates to true if that key is present otherwise false.
    # do something

or you can also do simply as:

if 'key' in my_dict:   # it will evaluates to true if that key is present otherwise false.
    # do something

The ways in which you can get the results are:

Which is better is dependent on 3 things:

  1. Does the dictionary 'normally has the key' or 'normally does not have the key'.
  2. Do you intend to use conditions like if...else...elseif...else?
  3. How big is dictionary?

Read More: http://paltman.com/try-except-performance-in-python-a-simple-test/

Use of try/block instead of 'in' or 'if':

try:
    my_dict_of_items[key_i_want_to_check]
except KeyError:
    # Do the operation you wanted to do for "key not present in dict".
else:
    # Do the operation you wanted to do with "key present in dict."

Dictionary in python has a get('key', default) method. So you can just set a default value in case there is no key.

values = {...}
myValue = values.get('Key', None)

Python dictionary has the method called __contains__. This method will return True if the dictionary has the key else returns False.

 >>> temp = {}

 >>> help(temp.__contains__)

Help on built-in function __contains__:

__contains__(key, /) method of builtins.dict instance
    True if D has a key k, else False.

Using ternary operator:

message = "blah" if 'key1' in dict else "booh"
print(message)

Well.. You will be familiar that searching a element's existence in a list or data means going through everything (at least for unordered list e.g dict.keys ).So Instead using Exception and Errors that arise normally we can avoid that complexity...

d={1:'a',2:'b'}
try:
    needed=d[3]
    print(needed)
except:
    print("Key doesnt exist")

I use the try/except; if an exception is throwed, than the key aren't present at the dictionary. example:

st = 'sdhfjaks'
d = {}
try:
    print d['st']
except Exception, e:
    print 'Key not in the dictionary'

Why not just use the has_key() method.

a = {}
a.has_key('b') => #False

a['b'] = 8
a.has_key('b') => #True