Python字典;相同键的总和 [英] Python dictionary; sum values of the same keys

查看:114
本文介绍了Python字典;相同键的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能很简单,但我只是一个初学者. 如果我有这本字典;

It might be simple but im just a beginner. If i have this dictionary;

ds = {"ABab": 6.25, "aBab": 6.25, "Abab": 6.25, "abab": 6.25, "ABab": 6.25, "aBab": 6.25, "Abab": 6.25, "abab": 6.25, "ABab": 6.25, "aBab": 6.25, "Abab": 6.25, "abab": 6.25, "ABab": 6.25, "aBab": 6.25, "Abab": 6.25, "abab": 6.25}

是否有创建此方法的方法?:

is there a way to create this?:

ds_new = {"ABab": 25, "aBab": 25, "Abab": 25, "abab": 25}

如果没有办法做到这一点,谢谢您一直在寻找它.

If there is not a way to do this, thank you foor looking in to it anyway.

推荐答案

如前所述,您不能将此数据存储在字典中.您可以将其存储为其他形式,例如元组列表.

As noted already, you can't store this data in a dictionary. You could store it in some other form such as a list of tuples.

ds = [("ABab", 6.25), ("aBab", 6.25), ("Abab", 6.25), ("abab", 6.25),
      ("ABab", 6.25), ("aBab", 6.25), ("Abab", 6.25), ("abab", 6.25),
      ("ABab", 6.25), ("aBab", 6.25), ("Abab", 6.25), ("abab", 6.25),
      ("ABab", 6.25), ("aBab", 6.25), ("Abab", 6.25), ("abab", 6.25)]

然后,您可以通过首先找到唯一的键,然后将以该键为第一个值的元组的值相加,制成总计的字典.

Then you can make a dictionary of the totals by first finding the unique keys and then summing the values of the tuples which have that key as their first value.

keys = set(k for k, _ in ds)
totals = {unique_key: sum(v for k, v in ds if k==unique_key) 
    for unique_key in keys}

或者另一种方式(可能更好)

Or another way (probably better)

totals = {}
for key, value in ds:
    totals[key] = totals.get(key, 0) + value

这篇关于Python字典;相同键的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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