Python 检查字典中是否已存在给定的密钥

Python 检查字典中是否已存在给定的密钥,python,dictionary,Python,Dictionary,在更新键的值之前,我想测试字典中是否存在键。 我编写了以下代码: if 'key1' in dict.keys(): print "blah" else: print "boo" 我认为这不是完成这项任务的最佳方式。有没有更好的方法来测试字典中的键?您不必调用键: if 'key1' in dict: print("blah") else: print("boo") 这与它使用字典的散列而不是调用键所做的线性搜索差不多。您不必调用键: if 'key1' in dict:

在更新键的值之前,我想测试字典中是否存在键。 我编写了以下代码:

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

我认为这不是完成这项任务的最佳方式。有没有更好的方法来测试字典中的键?

您不必调用键:

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

这与它使用字典的散列而不是调用键所做的线性搜索差不多。

您不必调用键:

if 'key1' in dict:
  print("blah")
else:
  print("boo")
这与它使用字典的散列而不是调用键所做的线性搜索差不多。

您可以将其缩短:

if 'key1' in dict:
    ...
然而,这充其量只是一种表面上的改进。为什么您认为这不是最好的方法?

您可以缩短:

if 'key1' in dict:
    ...

然而,这充其量只是一种表面上的改进。为什么您认为这不是最好的方法?

我建议改用
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}

我建议改用
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}
是测试数据库中是否存在密钥的预期方法

如果需要默认设置,则始终可以使用:

如果要始终确保任何键的默认值,可以重复使用或从模块中使用,如下所示:

from collections import defaultdict

d = defaultdict(int)

for i in range(100):
    d[i % 10] += 1
但一般来说,关键字中的
是最好的方法。

是测试密钥是否存在的理想方法

如果需要默认设置,则始终可以使用:

如果要始终确保任何键的默认值,可以重复使用或从模块中使用,如下所示:

from collections import defaultdict

d = defaultdict(int)

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

但一般来说,关键字in是最好的方法。

您可以使用in关键字测试字典中是否存在关键字:

d={'a':1,'b':2}

d#中的“a”可以使用in关键字测试字典中是否存在键:

d={'a':1,'b':2}
仅d#python2中的'a'(并且python2.7已经支持'in')
您可以使用
has_key()
方法:

if dict.has_key('xyz')==1:
    #update the value for the key
else:
    pass
d.get("key")
仅Python2:(Python2.7已经支持'in') 您可以使用
has_key()
方法:

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

仅供参考添加到克里斯。B(最佳答案):


工作也很好;原因是调用
int()
返回
0
,这是
defaultdict
在幕后(构建字典时)所做的,因此在文档中命名为“Factory Function”。

仅供参考。B(最佳答案):

工作也很好;原因是调用
int()
返回
0
,这是
defaultdict
在幕后(构建字典时)所做的,因此在文档中被称为“工厂函数”。

使用EAFP如何(请求原谅比许可更容易):

见其他SO帖子:

使用EAFP(请求原谅比允许更容易)怎么样

见其他SO帖子:


有关公认答案建议方法(10m循环)执行速度的更多信息:

  • mydict中的“键”
    运行时间1.07秒
  • mydict.get('key')
    运行时间1.84秒
  • mydefaultdict['key']
    运行时间1.07秒

因此,建议使用
中的
defaultdict
来反对
get

,以获取有关接受答案建议方法(10m循环)执行速度的更多信息:

  • mydict中的“键”
    运行时间1.07秒
  • mydict.get('key')
    运行时间1.84秒
  • mydefaultdict['key']
    运行时间1.07秒

因此,建议使用
中的
defaultdict
来反对
get

获得结果的方法是:

  • 如果您的字典有密钥(密钥)
  • 如果输入您的命令
  • 试/除块
哪个更好取决于三件事:

  • 字典是“通常有密钥”还是“通常没有密钥”
  • 你打算使用像if…else…elseif…else这样的条件吗
  • 这本字典有多大
  • 阅读更多:

    使用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."
    

    获得结果的方法有:

    • 如果您的字典有密钥(密钥)
    • 如果输入您的命令
    • 试/除块
    哪个更好取决于三件事:

  • 字典是“通常有密钥”还是“通常没有密钥”
  • 你打算使用像if…else…elseif…else这样的条件吗
  • 这本字典有多大
  • 阅读更多:

    使用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."
    

    python中的Dictionary有一个get('key',default)方法。因此,您可以设置一个默认值,以防没有键

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

    python中的Dictionary有一个get('key',default)方法。因此,您可以设置一个默认值,以防没有键

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

    Python dictionary有一个名为
    \uuuuuuuuuu包含的方法。如果字典具有键,则此方法将返回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.
    

    Python dictionary有一个名为
    \uuuuuuuuuu包含的方法。如果字典具有键,则此方法将返回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)
    

    使用三元运算符:

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

    您可以使用
    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')
    

    您可以使用
    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')
    

    共享使用布尔运算符检查键是否存在的另一种方法

    d = {'a': 1, 'b':2}
    keys = 'abcd'
    
    for k in keys:
        x = (k in d and 'blah') or 'boo'
        print(x) 
    
    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
    
    d.get("key")
    
    d= {'clear':0, 'copy':1, 'fromkeys':2, 'get':3, 'items':4, 'keys':5, 'pop':6, 'popitem':7, 'setdefault':8, 'update':9, 'values':10}
    
    print(d.get('key')) #None
    print(d.get('clear')) #0
    print(d.get('copy')) #1
    
    d= {'key':None}
    print(d.get('key')) #None
    print(d.get('key2')) #None
    
    print('key' in d) #True
    print('key2' in d) #False
    
    import dis
    dis.dis("'key' in d")
    #   1           0 LOAD_CONST               0 ('key')
    #               2 LOAD_NAME                0 (d)
    #               4 COMPARE_OP               6 (in)
    #               6 RETURN_VALUE
    
    dis.dis("d.get('key2')")
    #   1           0 LOAD_NAME                0 (d)
    #               2 LOAD_METHOD              1 (get)
    #               4 LOAD_CONST               0 ('key2')
    #               6 CALL_METHOD              1
    #               8 RETURN_VALUE