将元组列表转换为字典

时间:2009-08-05 14:15:50

标签: python list dictionary

我正在寻找一种方法来转换这样的元组列表:

[(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]

进入这样的字典:

{4:[1,2,3] ,15:[4,5,9,11,12], 23:[6,7,8,10]}

每个元组的第二个元素成为字典键,与该键相关联的所有第一个元组元素都存储在值列表中。

你能告诉我怎么做吗?

7 个答案:

答案 0 :(得分:47)

>>> from collections import defaultdict
>>> l= [(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
>>> d= defaultdict( list )
>>> for v, k in l:
...     d[k].append(v)
... 
>>> d
defaultdict(<type 'list'>, {23: [6, 7, 8, 10], 4: [1, 2, 3], 15: [4, 5, 9, 11, 12]})
>>> [ {k:d[k]} for k in sorted(d) ]
[{4: [1, 2, 3]}, {15: [4, 5, 9, 11, 12]}, {23: [6, 7, 8, 10]}]

答案 1 :(得分:13)

>>> a = [(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
>>> b = {}
>>> for i, j in a:
...     b.setdefault(j, []).append(i)
...
>>> b
{23: [6, 7, 8, 10], 4: [1, 2, 3], 15: [4, 5, 9, 11, 12]}
>>>

答案 2 :(得分:2)

l = [(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
d = {}
for v, k in l:
    d.setdefault(k, []).append(v)

答案 3 :(得分:2)

tuples = [(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
dicts = {}
for elem in tuples:
    try:
        dicts[elem[1]].append(elem[0])
    except KeyError:
        dicts[elem[1]] = [elem[0],]

答案 4 :(得分:2)

这样做:

from collections import defaultdict

def to_list_of_dicts(list_of_tuples):
    d = defaultdict(list)
    for x, y in list_of_tuples:
        d[y].append(x)
    return sorted([{x: y} for (x, y) in d.items()])

答案 5 :(得分:2)

这不是花哨但很简单

l = [(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
d = dict((k, [i[0] for i in l if i[1] == k]) for k in frozenset(j[1] for j in l))

好哇!

答案 6 :(得分:0)

for key, value in tuples:
    if d.get(key):
        d[key].append(value)
        continue
    d[key] =[value]