in is the intended way to test for the existence of a key in a dict.
d = {"key1": 10, "key2": 23}
if "key1" in d:
print("this will execute")
if "nonexistent key" in d:
print("this will not")
If you wanted a default, you can always use dict.get():
d = dict()
for i in range(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 either use dict.setdefault() repeatedly or defaultdict from the collections module, like so:
from collections import defaultdict
d = defaultdict(int)
for i in range(100):
d[i % 10] += 1
but in general, the in keyword is the best way to do it.
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).
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.
回答 5
我建议改用该setdefault方法。听起来它将满足您的所有要求。
>>> 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 above18>>>print d #The dictionary's been updated{'foo':'bar','baz':18}
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}
try:
my_dict_of_items[key_i_want_to_check]exceptKeyError:# 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."
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."
回答 10
仅限于Python 2 :(并且python 2.7 in已经支持)
您可以使用has_key()方法:
if dict.has_key('xyz')==1:#update the value for the keyelse:pass
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.
PythonDictionary clear()Removes all ItemsPythonDictionary copy()ReturnsShallowCopy of a DictionaryPythonDictionary fromkeys()Creates dictionary from given sequence
PythonDictionary get()ReturnsValue of TheKeyPythonDictionary items()Returns view of dictionary (key, value) pair
PythonDictionary keys()ReturnsViewObject of AllKeysPythonDictionary pop()Removesand returns element having given key
PythonDictionary popitem()Returns&RemovesElementFromDictionaryPythonDictionary setdefault()InsertsKeyWith a ValueifKeyisnotPresentPythonDictionary update()Updates the DictionaryPythonDictionary values()Returns view of all values in dictionary
Python Dictionary clear() Removes all Items
Python Dictionary copy() Returns Shallow Copy of a Dictionary
Python Dictionary fromkeys() Creates dictionary from given sequence
Python Dictionary get() Returns Value of The Key
Python Dictionary items() Returns view of dictionary (key, value) pair
Python Dictionary keys() Returns View Object of All Keys
Python Dictionary pop() Removes and returns element having given key
Python Dictionary popitem() Returns & Removes Element From Dictionary
Python Dictionary setdefault() Inserts Key With a Value if Key is not Present
Python Dictionary update() Updates the Dictionary
Python Dictionary values() Returns view of all values in dictionary
The brutal method to check if the key already exists may be the get() method:
d.get("key")
The other two interesting methods items() and keys() sounds like too much of work. So let’s examine if get() is the right method for us. We have our dict d:
>>> temp ={}>>> help(temp.__contains__)Help on built-in function __contains__:
__contains__(key,/) method of builtins.dict instance
Trueif D has a key k,elseFalse.
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.
回答 14
共享使用布尔运算符检查密钥是否存在的另一种方法。
d ={'a':1,'b':2}
keys ='abcd'for k in keys:
x =(k in d and'blah')or'boo'print(x)
Sharing one more way of checking if a key exists using boolean operators.
d = {'a': 1, 'b':2}
keys = 'abcd'
for k in keys:
x = (k in d and 'blah') or 'boo'
print(x)
This returns
>>> blah
>>> blah
>>> boo
>>> boo
Explanation
First you should know that in Python, 0, None, or objects with zero length evaluate to False. Everything else evaluates to True. Boolean operations are evaluated left to right and return the operand not True or False.
Let’s see an example:
>>> 'Some string' or 1/0
'Some string'
>>>
Since 'Some string' evaluates to True, the rest of the or is not evaluated and there is no division by zero error raised.
But if we switch the order 1/0 is evaluated first and raises an exception:
>>> 1/0 or 'Some string'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>>
We can use this for pattern for checking if a key exists.
(k in d and 'blah')
does the same as
if k in d:
'blah'
else:
False
This already returns the correct result if the key exists, but we want it to print ‘boo’ when it doesn’t. So, we take the result and or it with 'boo'
>>> False or 'boo'
'boo'
>>> 'blah' or 'boo'
'blah'
>>>
回答 15
您可以使用for循环遍历字典并获取要在字典中找到的键的名称,然后使用if条件检查其是否存在:
dic ={'first':12,'second':123}for each in dic:if each =='second':print('the key exists and the corresponding value can be updated in the dictionary')
You can use for loop to iterate over the dictionary and get the name of key you want to find in the dictionary, after that check if it exist or not using if condition:
dic = {'first' : 12, 'second' : 123}
for each in dic:
if each == 'second':
print('the key exists and the corresponding value can be updated in the dictionary')