首页 文章

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

提问于
浏览
2407

我想在更新密钥的值之前测试字典中是否存在密钥 . 我写了以下代码:

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

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

19 回答

  • 2

    只是一个FYI加入克里斯 . B(最佳答案):

    d = defaultdict(int)
    

    也适用;原因是调用 int() 返回 0 这是幕后的 defaultdict (构建字典时),因此文档中的名称为"Factory Function" .

  • 12

    要检查,您可以使用 has_key() 方法

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

    如果你想要一个值,那么你可以使用 get() 方法

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

    如果你想要一个元组或列表或字典或任何字符串作为默认值作为返回值,那么使用 get() 方法

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

    有关接受答案的建议方法(10米循环)的速度执行的其他信息:

    • 'key' in mydict 经过时间1.07秒

    • mydict.get('key') 经过时间1.84秒

    • mydefaultdict['key'] 经过时间1.07秒

    因此,建议对 get 使用 indefaultdict .

  • 233

    我用的是try / except;如果抛出异常,则字典中不存在密钥 . 例:

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

    python中的字典有一个get('key',default)方法 . 所以你可以设置一个默认值,以防没有密钥 .

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

    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.
    
  • 28

    The ways in which you can get the results are:

    • if your_dict.has_key(key)Removed in Python 3

    • 如果在your_dict中输入密钥

    • 尝试/除块

    Which is better is dependent on 3 things:

    • 字典是'normally has the key'还是'normally does not have the key' .

    • 你是否打算使用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."
    
  • -5

    你可以缩短这个:

    if 'key1' in dict:
        ...
    

    然而,这充其量只是一种美容改善 . 为什么你认为这不是最好的方法?

  • 11

    您不必调用密钥:

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

    这将是faster,因为它使用字典的散列而不是进行线性搜索,调用键会这样做 .

  • 6

    如果您知道要查找哪个密钥(密钥名称),最简单的方法是:

    # 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
    
  • 16

    嗯..你会很熟悉在列表或数据中搜索元素的存在意味着遍历所有内容(至少对于无序列表,例如dict.keys) . 因此,使用通常出现的异常和错误,我们可以避免这种复杂性......

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

    如何使用EAFP(更容易请求宽恕而非许可):

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

    查看其他SO帖子:

    Using try vs if in python

    Checking for member existence in Python

  • 20

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

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

    在变更之前检查字典中是否存在键的常见用法是默认初始化值(例如,如果您的值是列表,并且您希望确保有一个空列表,您可以将其追加到插入键的第一个值时) . 在这种情况下,您可能会发现collections.defaultdict()类型是有意义的 .

    在旧代码中,您可能还会发现 has_key() 的一些用法,这是一种不推荐使用的方法,用于检查字典中是否存在键(仅使用 key_name in dict_name ) .

  • 42

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

    不会为dict中的值打印boo,而是通过打印key1的值来确认它的存在来实现目标 .

  • 0

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

    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
    
  • 77

    in 是测试 dict 中是否存在密钥的预期方法 .

    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
    

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

  • 2454

    使用三元运算符:

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

    为什么不使用has_key()方法 .

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

相关问题