python 将两字典相同key的value合并成一个数组

发布时间:2024年01月18日

python 将两字典相同key的value合并成一个数组

#  dic_a = {"key1":1,"key5":2}
#  dic_b = {"key1":3,"key4":4}
#  result_dic = {"key1":[1,3],"key4":[4],"key5":[2]}
def merge_two_dict(dic_a: dict, dic_b: dict):
    result_dic = {}
    if not dic_a:
        result_dic = dic_b
    elif not dic_b:
        result_dic = dic_a
    else:
        for k, v in dic_a.items():
            for m, n in dic_b.items():
                if k == m:
                    result_dic[k] = []
                    result_dic[k] += dic_a[k]
                    result_dic[k] += dic_b[k]
                    dic_a[k] = result_dic[k]
                    dic_b[k] = result_dic[k]
                else:
                    result_dic[k] = dic_a[k]
                    result_dic[m] = dic_b[m]
    return result_dic
文章来源:https://blog.csdn.net/qq_26545503/article/details/135677071
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。