python dict学习笔记

dict.setdefault(key, default=None)

  • 描述:

   Python 字典 setdefault() 函数和get() 方法类似, 如果键不存在于字典中,将会添加键并将值设为默认值。

  • 备注:

  与get()相同点:如果key存在,返回对应value,如果不存在,返回设定的值

  与get()不同点:如果key不存在,setdefault()更新dict,get()不更新dict

  • 参考链接:

  http://www.runoob.com/python/att-dictionary-get.html

  http://www.runoob.com/python/att-dictionary-setdefault.html

  • 示例:
[6]:
dict = {'runoob': '菜鸟教程', 'google': 'Google 搜索'}
print("Value : " , dict.setdefault('runoob', None))
print("Value : " , dict.setdefault('Taobao', '淘宝'))
print("new dict: ", dict)
Value :  菜鸟教程
Value :  淘宝
new dict:  {'runoob': '菜鸟教程', 'google': 'Google 搜索', 'Taobao': '淘宝'}
[7]:
dict = {'runoob': '菜鸟教程', 'google': 'Google 搜索'}
print("Value : %s" %  dict.get('runoob'))
print("Value : %s" %  dict.get('baidu', "Never"))
print("new dict is: ", dict)
Value : 菜鸟教程
Value : Never
new dict is:  {'runoob': '菜鸟教程', 'google': 'Google 搜索'}

update更新字典

  • 描述:

   增加字典,或更改字典key对应的value

  • 示例:
[13]:
original_params = {'n_estimators': 1000, 'max_leaf_nodes': 4,
                   'min_samples_split': 5}
params = original_params
setting  = {'learning_rate': 0.1, 'max_leaf_nodes': 2}
params.update(setting)
print('dict after update :\n\n',params)
dict after update :

 {'n_estimators': 1000, 'max_leaf_nodes': 2, 'min_samples_split': 5, 'learning_rate': 0.1}