如何使用默认值检查字典中的键值

use*_*467 0 python

我怎么能理解字典中没有键和值?如果可能的话,我将使用好像新的值不在字典中添加它.例如

d = {1:"k", 2:"l"}
Run Code Online (Sandbox Code Playgroud)

如果3不在列表中,则代码应该理解并将其作为具有空值的字典的新项

d = {1:"k", 2:"l", 3:"null"}
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 7

你可以使用dict.setdefault:

d.setdefault(3,"null")
Run Code Online (Sandbox Code Playgroud)

演示:

>>> d = {1:"k", 2:"l"}
>>> d.setdefault(3,"null")    # if key is found then return the value else
                              # set the new key and return the new value  
'null'                     
>>> d
{1: 'k', 2: 'l', 3: 'null'}
Run Code Online (Sandbox Code Playgroud)

帮助dict.setdefault:

>>> dict.setdefault?
Type:       method_descriptor
String Form:<method 'setdefault' of 'dict' objects>
Namespace:  Python builtin
Docstring:  D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
Run Code Online (Sandbox Code Playgroud)