How to add or increment a dictionary entry?

前端 未结 6 843
时光取名叫无心
时光取名叫无心 2020-12-04 16:19

I\'m currently re-engaging with Python after a long absence and loving it. However, I find myself coming across a pattern over and over. I keep thinking that there must be a

6条回答
  •  -上瘾入骨i
    2020-12-04 16:44

    You can also take advantage of the control structure in exception handling. A KeyError exception is thrown by a dictionary when you try to assign a value to a non-existent key:

    my_dict = {}
    try:
        my_dict['a'] += 1
    except KeyError, err:    # in 2.6: `except KeyError as err:`
        my_dict['a'] = 1
    

提交回复
热议问题