将元组列表映射到字典中 [英] Map list of tuples into a dictionary

查看:139
本文介绍了将元组列表映射到字典中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从数据库的一个表中提取了一个元组列表,该表看起来像( key foreignkey value ).键和外键之间存在多对一的关系,我想将其转换为由外键索引的字典,该外键包含该外键的所有值的总和,即{ foreignkey sumof()}.我写的东西很冗长:

I've got a list of tuples extracted from a table in a DB which looks like (key , foreignkey , value). There is a many to one relationship between the key and foreignkeys and I'd like to convert it into a dict indexed by the foreignkey containing the sum of all values with that foreignkey, i.e. { foreignkey , sumof( value ) }. I wrote something that's rather verbose:

myDict = {}
for item in myTupleList:
    if item[1] in myDict:
        myDict [ item[1] ] += item[2]
    else:
        myDict [ item[1] ] = item[2]

,但在看到这些 两个表达我想做的事情的一种更简洁的方式.如果是重复的话,我会错过它,如果您可以提供链接,则会删除该问题.

but after seeing this question's answer or these two there's got to be a more concise way of expressing what I'd like to do. And if this is a repeat, I missed it and will remove the question if you can provide the link.

推荐答案

假定所有值均为int,则可以使用defaultdict使其更容易:

Assuming all your values are ints, you could use a defaultdict to make this easier:

from collections import defaultdict

myDict = defaultdict(int)

for item in myTupleList:
    myDict[item[1]] += item[2]

defaultdict就像字典,除非您尝试获取不存在的键,否则它会填充可调用对象返回的值-在这种情况下,int,在不带参数的情况下调用时将返回0

defaultdict is like a dictionary, except if you try to get a key that isn't there it fills in the value returned by the callable - in this case, int, which returns 0 when called with no arguments.

更新:感谢 @gnibbler 提醒我,但是元组可以在for循环中解包:

UPDATE: Thanks to @gnibbler for reminding me, but tuples can be unpacked in a for loop:

from collections import defaultdict

myDict = defaultdict(int)

for _, key, val in myTupleList:
    myDict[key] += val

在这里,三项元组被解包到变量_keyval中. _是Python中常用的占位符名称,用于表示该值并不十分重要.使用此方法,我们可以避免繁琐的item[1]item[2]索引.如果myTupleList中的元组的大小不一样,我们就不能依靠它,但是我敢打赌它们是相同的.

Here, the 3-item tuple gets unpacked into the variables _, key, and val. _ is a common placeholder name in Python, used to indicate that the value isn't really important. Using this, we can avoid the hairy item[1] and item[2] indexing. We can't rely on this if the tuples in myTupleList aren't all the same size, but I bet they are.

(我们还避免了某些情况,因为有人认为数组是1索引的,这是我第一次阅读代码时的想法.阅读问题,但是,在上面的循环中,很明显myTupleList是三个元素的元组,而我们不需要第一个.)

(We also avoid the situation of someone looking at the code and thinking it's broken because the writer thought arrays were 1-indexed, which is what I thought when I first read the code. I wasn't alleviated of this until I read the question. In the above loop, however, it's obvious that myTupleList is a tuple of three elements, and we just don't need the first one.)

这篇关于将元组列表映射到字典中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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