python:实现快速更新字典

python开发中,如何对字典中的元素进行快速更新?

首先安装模块:

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

※更新一层字典

第一种方式:[key]
smart_girl["age"] = 35 

说明:字典中存在key时为修改value、不存在key则是添加key-value到字典中

第二种方式:update方法(使用关键字参数)
smart_girl.update(name = "tyson", age = 80) 

说明:update方法执行时,dict中未找到对应的key,也会自动添加一个key-value到字典中

第三种方式:update方法(使用解包字典)
 smart_girl.update(**{"age":50}) 

等同于

 smart_girl.update(age=50) 
第四种方式:update方法(使用字典对象)
smart_girl.update({"name": "da ye", "age" : 30, "address" : "beijing "}) 

说明:update方法里面也可以直接处理一个dict对象

※更新多层字典

python修改多层嵌套字典里面的值
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

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值