首先安装模块:
pip install update_dict
github文档:https://github.com/yutu-75/update_dict
源码如下:
def update_dict(d1, d2): # d1是字典,d2是{键:值}
if not isinstance(d1, dict) or not isinstance(d2, dict):
raise TypeError('Params of update_dict should be dicts')
for i in d1:
if d2.get(i, None) is not None:
d1[i] = d2[i]
if isinstance(d1[i], dict):
update_dict(d1[i], d2)
return
smart_girl["age"] = 35
说明:字典中存在key时为修改value、不存在key则是添加key-value到字典中
smart_girl.update(name = "tyson", age = 80)
说明:update方法执行时,dict中未找到对应的key,也会自动添加一个key-value到字典中
smart_girl.update(**{"age":50})
等同于
smart_girl.update(age=50)
smart_girl.update({"name": "da ye", "age" : 30, "address" : "beijing "})
说明:update方法里面也可以直接处理一个dict对象
def update_dict(d1, d2): # d1是字典,d2是{键:值}
if not isinstance(d1, dict) or not isinstance(d2, dict):
raise TypeError('Params of update_dict should be dicts')
for i in d1:
if d2.get(i, None) is not None:
d1[i] = d2[i]
if isinstance(d1[i], dict):
update_dict(d1[i], d2)
return
d_data ={
'a': {
"b": {
"c": {
"d": 'qwq'
}
}, "b2": "qwq"
}, 'aa': {"bb":
{
"cc": "qwqcc"
}
}
}
print(d_data)
u_data = update_dict(d_data,{"b2":{'这是集合b2'},'d':'这是d'})
print(u_data)
结果:
{'a': {'b': {'c': {'d': 'qwq'}}, 'b2': 'qwq'}, 'aa': {'bb': {'cc': 'qwqcc'}}}
{'a': {'b': {'c': {'d': '这是d'}}, 'b2': {'这是集合b2'}}, 'aa': {'bb': {'cc': 'qwqcc'}}}
参考自:https://blog.csdn.net/cadi2011/article/details/86610985
https://blog.csdn.net/yutu75/article/details/123496890