简体   繁体   English

给定一个 [string, number] 元组列表,创建一个字典,其中键是字符串的第一个字符,值是数字的总和

[英]Given a list of [string, number] tuples, create a dictionary where keys are the first characters of strings and the values are sums of the numbers

I have a list of tuples, where first object is a string and second one is a number.我有一个元组列表,其中第一个 object 是一个字符串,第二个是一个数字。 I need to create a dictionary with using first letter of the string as a key and number (or I need to add some numbers if keys will be the same) as a value.我需要创建一个字典,使用字符串的第一个字母作为键和数字(或者如果键相同,我需要添加一些数字)作为值。 for example:例如:

input输入

lst = [('Alex', 5), ('Addy', 7), ('Abdul', 2), ('Bob', 6), ('Carl', 8), ('Cal', 4)]

output output

dct = {'A': 14, 'B': 6, 'C': 12}

The most simple, straightforward and naive way is:最简单、直接和幼稚的方法是:

dct = {}
for k, v lst:
    if k in v:
        dct[k] += v
    else:
        dct[k] = v

There are ways to progressively be more clever, the first is probably to use .get with the default:有一些方法可以逐渐变得更聪明,第一种可能是使用.get和默认值:

dct = {}
for k, v in lst:
    dct[k] = dct.get(k, 0) + v

Finally, you can use a collections.defaultdict , which takes a "factory" function which will be called if the key is not there, use int as the factor:最后,您可以使用collections.defaultdict ,它采用“工厂” function 如果密钥不存在将被调用,使用int作为因素:

from collections import defaultdict
dct = defaultdict(int)
for k, v in lst:
    dct[k] += v

NOTE: it is usually safer to create a regular dict out of this, to avoid the default behavior:注意:创建一个常规的字典通常更安全,以避免默认行为:

dct = dict(dct)

Or even甚至

dct.default_factory = None

Finally, one of the more flexible ways is to create your own dict subclass and use __missing__ , this is useful if need access to the key when you are making the default value, so not particularly more helpful here, but for completion's sake:最后,一种更灵活的方法是创建自己的dict子类并使用__missing__ ,如果在设置默认值时需要访问键,这很有用,所以在这里不是特别有用,但为了完成:

class AggDict(dict):
    def __missing__(self, key):
        return 0

dct = AggDict()
for k, v in dct:
    dct[k] += v

Use a defaultdict :使用defaultdict

dct = defaultdict(int) # default to 0

for name, val in lst:
    dct[name[0]] += val

dct = dict(dct) # get rid of default value

You could use Counter from collections to convert the tuples to countable key/values, then use reduce from functools to add them together:您可以使用 collections 中的 Counter 将元组转换为可计数的键/值,然后使用 functools 中的 reduce 将它们相加:

from collections import Counter
from functools   import reduce

lst = [('Alex', 5), ('Addy', 7), ('Abdul', 2), ('Bob', 6), ('Carl', 8), ('Cal', 4)]

dst = reduce(Counter.__add__,(Counter({k[:1]:v}) for k,v in lst))

# Counter({'A': 14, 'C': 12, 'B': 6})

暂无
暂无

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

相关问题 如何将给定值和键作为元组的元组创建字典 - How to create a dictionary given values and keys as tuples of tuples 给定一个以字符串列表作为其值的字典,您将如何检索列表包含所有其他列表唯一的字符串的所有键? - Given a dictionary with lists of strings as their values, how would you retrieve all keys where the list contains a string unique to all other lists? 创建字典,其中值是转换为字符串的键 - Create dictionary where values are keys transformed to strings Python将字典中的键具有多个值的字典转换为元组列表 - Python convert dictionary where keys have multiple values into list of tuples 将字符串的字符与字典的键匹配,如果匹配,则将字符串转换为键的值 - Matching characters of a string with keys of a dictionary and converting strings to values of keys if matched 如何创建一个字典,其中键是列表中的元素,值是从1到n的数字? - How to create a dictionary where the keys are the elements in a list and the values are numbers from 1 to n? 从字典键和值中获取元组列表 - getting a list of tuples out of dictionary keys and values 从2个键和2个元组的字典创建排序列表 - Create sorted list from dictionary of 2 keys and 2 tuples Python - 如果给定字典按值的顺序创建键列表 - Python - If given dictionary create a list of keys in order of the values 如何在给定列表和元组元组的情况下创建将字符串映射到集合的字典? - How do I create a dictionary mapping strings to sets given a list and a tuple of tuples?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM