简体   繁体   English

获取字典中的值之和

[英]Get a sum of values inside a dictionary

I have a dictionary where key is a country name and value is a list of two or 1 numbers. 我有一本字典,其中的键是国家名称,值是两个或一个数字的列表。 I need to get the sum of those two values in a form of a dictionary where key is the country and the value is the sum. 我需要以字典的形式获取这两个值的总和,其中键是国家/地区,而值是总和。

I've tried using sum() but I get an error that states - can only concatenate list (not "int") to list. 我尝试使用sum(),但收到一条错误消息,指出只能将列表(而不是“ int”)连接到列表。

country_home = sorted(Counter(data['home_team']).most_common()) # gives back ('America', 18)
country_away = sorted(Counter(data['away_team']).most_common()) # gives back ('America', 10)

        country_away = sorted(Counter(data['away_team']).most_common())
        d = defaultdict(list)
        for a, b in country_home + country_away:
            d[a].append(b)
        print(d) # gives back {'America': [18, 10], 'Canada': [37, 65], 'Mexico: [10], ...}

The expected result is a list or a dictionary 预期的结果是列表或字典

{'America': [28], 'Canada': [102], ... }

Why don't you just do: 您为什么不这样做:

Counter(data['home_team'] + data['away_team']).most_common()

Example: 例:

from collections import Counter, OrderedDict
data = {
    'home_team': 'America America  America  America America America Canada'.split(),
    'away_team': 'America America  America  America America America Canada'.split()
}

print(OrderedDict(Counter(data['home_team'] + data['away_team']).most_common()))

Output : 输出:

OrderedDict([('America', 12), ('Canada', 2)])

If you don't care about order use dict(..) instead of OrderedDict(..) 如果您不关心订单,请使用dict(..)而不是OrderedDict(..)

Or you can do this: 或者您可以这样做:

  print(dict((Counter(data['home_team'])+ Counter(data['away_team'])).most_common()))

Without harming the original dictionary you can try: 在不损害原始词典的情况下,您可以尝试:

a = {'America':[18,20],'Canada':[37,65],'c':[4,5,6]}
b = {x:a[x] for x in a}
b = {x : [] for x in b}
for i in a:
    b[i].append(sum(a[i]))
print(b)

Output: 输出:

{'America': [38], 'Canada': [102], 'c': [15]}

This way whenever a new key is added to the first dictionary, it will be added to diciontary b . 这样,每当将新键添加到第一个字典时,它将被添加到字典b

With minimal changes to your code, following should work. 只需对代码进行最少的更改,即可完成以下工作。

     country_away = sorted(Counter(data['away_team']).most_common())
        d = defaultdict(list)
        for a, b in country_home + country_away:
            d[a].append(b)
            d[a] = [sum(d[a])] # sum up the list
        print(d) # should give back {'America': [28], 'Canada': [102], 'Mexico': [10]...}

Is this what you wanted to do? 这就是你想做的吗?

Cheers 干杯

You can process the dictionary using dict comprehension 您可以使用dict理解来处理字典

d = {'America':[18,20],'Canada':[37,65],'c':[4,5,6]}
res = {k:[sum(v)] for k,v in d.items()}
print(res)

Output: 输出:

{'America': [38], 'Canada': [102], 'c': [15]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM