Python update a key in dict if it doesn't exist

前端 未结 5 1611
清歌不尽
清歌不尽 2020-12-24 11:17

I want to insert a key-value pair into dict if key not in dict.keys(). Basically I could do it with:

if key not in d.keys():
    d[key] = value
5条回答
  •  伪装坚强ぢ
    2020-12-24 11:43

    Use dict.setdefault():

    >>> d = {1: 'one'}
    >>> d.setdefault(1, '1')
    'one'
    >>> d    # d has not changed because the key already existed
    {1: 'one'}
    >>> d.setdefault(2, 'two')
    'two'
    >>> d
    {1: 'one', 2: 'two'}
    

提交回复
热议问题