d =dict(name='孙悟空',age=18,gender='男')
result = d.setdefault('name','猪八戒')print(d)print("result = ", result)
result = d.setdefault('hello','猪八戒')print(d)print("result = ", result)
4.3 update([other])
将其他的字典中的key-value添加到当前字典中
如果有重复的key,则后边的会替换到当前的
d ={'a':1,'b':2,'c':3}print(d)
d2 ={'d':4,'e':5,'f':6,'a':7}
d.update(d2)print(d)
5. 删除字典
5.1 可以使用 del 来删除字典中的 key-value
d ={'a':1,'b':2,'c':3}print(d)del d['a']del d['b']print(d)# del d['z'] z不存在,报错
5.2 popitem()
随机删除字典中的一个键值对,一般都会删除最后一个键值对
删除之后,它会将删除的key-value作为返回值返回
返回的是一个元组,元组中有两个元素,第一个元素是删除的key,第二个是删除的value
当使用popitem()删除一个空字典时,会抛出异常 KeyError: ‘popitem(): dictionary is empty’
d ={'a':1,'b':2,'c':3}print(d)
result = d.popitem()print(d)print("result = ", result)
5.3 pop(key[, default])
根据key删除字典中的key-value
会将被删除的value返回!
如果删除不存在的key,会抛出异常
如果指定了默认值,再删除不存在的key时,不会报错,而是直接返回默认值
d ={'a':1,'b':2,'c':3}print(d)
result = d.pop('c')print(d)
result = d.pop('z','这是默认值')print(d)print("result = ", result)