检查给定的键是否已经存在于字典中
我想在更新密钥的值之前testing一个字典中是否存在一个密钥。 我写了下面的代码:
if 'key1' in dict.keys(): print "blah" else: print "boo" 我认为这不是完成这个任务的最好方法。 有没有更好的方法来testing字典中的一个键?
  in是用于testingdict是否存在密钥的预期方式。 
 d = dict() for i in xrange(100): key = i % 10 if key in d: d[key] += 1 else: d[key] = 1 
 如果你想要一个默认的,你总是可以使用dict.get() : 
 d = dict() for i in xrange(100): key = i % 10 d[key] = d.get(key, 0) + 1 
  …如果你想确保任何键的默认值,你可以使用collections模块的defaultdict ,如下所示: 
 from collections import defaultdict d = defaultdict(lambda: 0) for i in xrange(100): d[i % 10] += 1 
…但一般来说,关键字是最好的办法。
您不必拨打电话:
 if 'key1' in dict: print "blah" else: print "boo" 
这会更快,因为它使用字典的哈希,而不是做一个线性search,这将调用键。
您可以使用in关键字testing字典中是否存在密钥:
 d = {'a': 1, 'b': 2} 'a' in d # <== evaluates to True 'c' in d # <== evaluates to False 
 在变异之前检查字典中键是否存在的一个常见用法是默认初始化该值(例如,如果您的值是列表,并且您希望确保存在可以追加的空列表当插入一个键的第一个值)。 在这些情况下,您可能会发现collections.defaultdict()types是有用的。 
 在较旧的代码中,您也可能会发现has_key()一些用法, has_key()是一种用于检查字典中是否存在键的不赞成使用的方法(只是key_name in dict_name使用key_name in dict_name )。 
你可以缩短这个:
 if 'key1' in dict: ... 
不过,这至less是一个美容改善。 你为什么认为这不是最好的方法?
 我会build议使用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 above 18 >>> print d #The dictionary's been updated {'foo': 'bar', 'baz': 18} 
有关接受答案的build议方法(10m循环)的速度执行的其他信息:
-   'key' in mydict经过时间1.07秒的'key' in mydict
-   mydict.get('key')已用时间1.84秒
-   mydefaultdict['key']经过时间1.07秒
 因此build议不要使用in或defaultdict 。 
 为了检查你可以使用has_key()方法 
 if dict.has_key('key1'): print "it is there" 
 如果你想要一个值,那么你可以使用get()方法 
 a = dict.get('key1', expeced_type) 
 如果您想要一个元组或列表或字典或任何string作为默认值作为返回值,则使用get()方法 
 a = dict.get('key1', {}).get('key2', []) 
只是一个FYI添加到克里斯。 B(最佳答案):
 d = defaultdict(int) 
 也可以工作; 原因在于调用int()返回0 ,这是defaultdict在幕后(构build字典时)的内容,因此文档中名称为“Factory Function”。 
你可以使用has_key()方法:
 if dict.has_key('xyz')==1: #update the value for the key else: pass 
  或者如果没有finddict.get方法来设置默认值: 
 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 
你可以得到结果的方式是:
- 如果your_dict.has_key(key) 在Python 3中被移除
- 如果键入your_dict
- 尝试/除了块
哪个更好取决于3件事情:
- 字典“通常有钥匙”还是“通常没有钥匙”?
- 你是否打算使用if … else … elseif … else的条件?
- 字典有多大?
阅读更多: http : //paltman.com/try-except-performance-in-python-a-simple-test/
使用try / block代替'in'或'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." 
怎么样使用EAFP(容易请求宽恕比权限):
 try: blah = dict["mykey"] # key exists in dict except: # key doesn't exist in dict 
查看其他SOpost:
使用尝试与如果在Python或
在Python中检查成员存在
 print dict.get('key1', 'blah') 
不会打印字典中的值的嘘声,而是通过打印key1的值来确认它的存在来实现目标。
  Python中的字典有一个get('key',default)方法。 所以你可以设置一个默认值,以防没有密钥。 values = {...} myValue = values.get('Key', None) 
  Python字典有一个名为__contains__的方法。 如果字典有关键字,则返回True,否则返回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. 
使用三元运算符:
 message = "blah" if 'key1' in dict else "booh" print(message) 
最简单的一个就是如果你知道哪个键(键名)要查找:
 # 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 
或者你也可以简单地做:
 if 'key' in my_dict: # it will evaluates to true if that key is present otherwise false. # do something