从词典列表创建唯一的词典列表,该词典列表包含相同的键但值不同 [英] Creating a unique list of dictionaries from a list of dictionaries which contains same keys but different values

查看:88
本文介绍了从词典列表创建唯一的词典列表,该词典列表包含相同的键但值不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我得到了这样的词典列表:

suppose i have been given a list of dictionaries like this :

[{"id":1, "symbol":'A', "num":4}, {"id":2, "symbol":'A', "num":3}, {"id":1, "symbol":'A', "num":5}, {"id":2, "symbol":'B', "num":1}]

现在,我必须创建一个字典或更改当前字典,以使(id,symbol)一起唯一,并且num值是字典中具有该(id,symbol)的所有值的总和,以便新字典或当前字典看起来像这样:

Now, i have to create a dictionary or alter the current one such that (id, symbol) together are unique and the num value is the sum of all the values present in the dict with that (id,symbol) so that the new dict or the current dict looks something like this:

[{"id":1, "symbol":'A', "num":9}, {"id":2, "symbol":'A', "num":3}, {"id":2, "symbol":'B', "num":1}]

推荐答案

这是使用纯Python的解决方案.

Here's a solution with plain python.

dlst = [{"id":1, "symbol":'A', "num":4}, {"id":2, "symbol":'A', "num":3},
    {"id":1, "symbol":'A', "num":5}, {"id":2, "symbol":'B', "num":1}]


# Create a dict where keys are tuples of (id,symbol), values are num

combined_d = {}

for d in dlst:
    id_sym = (d["id"], d["symbol"])
    if id_sym in combined_d:
        combined_d[id_sym] += d["num"]
    else:
        combined_d[id_sym] = d["num"]

# create a list of dictionaries from the tuple-keyed dict

result = []

for k, v in combined_d.items():
    d = {"id": k[0], "symbol": k[1], "num": v}
    result.append(d)

print(result)

它可以做您想要的,但是结果列表没有排序,因为它是根据字典构建的.

It does what you want, but the resulting list is not sorted, as it's built from a dictionary.

这篇关于从词典列表创建唯一的词典列表,该词典列表包含相同的键但值不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆