叼花硬汉 2009-10-21 19:05 采纳率: 0%
浏览 371
已采纳

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

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

  • 写回答

19条回答 默认 最新

  • perhaps? 2009-10-21 19:10
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(18条)

报告相同问题?

悬赏问题

  • ¥15 luckysheet
  • ¥25 关于##爬虫##的问题,如何解决?:
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题