python合并多个dict---合并多个字典值---字典值相加

发布时间:2024年01月23日

主要是借助Counter、函数传参和+运算符重载!各有优劣!

多个dict同key值相加

collection.Counter

借助collections.Counter,但是它只适用于值为整数或者小数类型**,否则报错!**

from collections import Counter
a = {"1":2}
b = {"1":30}
print(dict(Counter(a)+Counter(b)))

a = {"1":2.0}
b = {"1":30.5}
print(dict(Counter(a)+Counter(b)))

在这里插入图片描述

传参

借助函数传参,但是不能同值合并。如下:

a = {"1":2}
b = {"2":3}

def merge_dicts(**kwargs):
    return kwargs

merge_dicts(**a, **b)

在这里插入图片描述

重载+号

from collections.abc import Iterable

class MyDict:
    def __init__(self, dic):
        self._dic = dic
    
    def __add__(self, other):
        new_dic = self._dic
        for k, v in other._dic.items():
            if k in new_dic:
                if isinstance(v, Iterable) or isinstance(v, int) or isinstance(v, float):
                    new_dic[k] += v
            else:
                new_dic[k] = v
        self._dic = new_dic
        return self._dic
    
a = MyDict({1: "11a"})
b = MyDict({10: 21, 1: "11b"})
a+b

在这里插入图片描述

多个dict合并

两种方法

# 方法一, 借助函数传参
a = {"1":2}
b = {"2":3}

def update(**kwargs):
    return kwargs

update(**a, **b)

输出如下:
在这里插入图片描述

# 方法二
from collections import Counter
a = {"1":2}
b = {"2":3}
dict(Counter(a)+Counter(b))

在这里插入图片描述

练习

请您对以上三种方法的弊端进行复现。

文章来源:https://blog.csdn.net/mantoureganmian/article/details/135776265
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。