无法将元组的元组转换为字典

时间:2018-12-11 05:01:49

标签: python-3.x dictionary tuples

我试图将一个元组的元组转换为字典,但是它没有给我正确的值。

t = ((1,1),(1,10),(1,100),(1,1000),(2,2),(2,20),(2,200),(2,2000),(3,3), 
    (3,30),(3,300),(3,3000),(4,4),(4,40),(4,400),(4,4000))
d = dict(t)

这样做使我的价值

d = {1:1000,2:2000,3:3000,4:4000}

好像我尝试交换键值对的值一样,它给出了所有类似的值

d = dict((x,y) for y,x in t)
d = {1:1,10:1,100:1,1000:1,2:2,20:2,200:2,2000:2,} etc

我想要的是

 d = {1:1,1:10,1:100,1:1000,2:2,2:20,2:200,2:2000...... 4:4000}

1 个答案:

答案 0 :(得分:0)

Python字典不支持重复键。

相反,您可以使用collections.defaultdict()将多个值(列表)映射到同一键:

from collections import defaultdict

t = ((1,1),(1,10),(1,100),(1,1000),(2,2),(2,20),(2,200),(2,2000),(3,3), 
     (3,30),(3,300),(3,3000),(4,4),(4,40),(4,400),(4,4000))

d = defaultdict(list)
for x, y in t:
    d[x].append(y)

print(d)

哪个给出以下字典:

defaultdict(<class 'list'>, {1: [1, 10, 100, 1000], 2: [2, 20, 200, 2000], 3: [3, 30, 300, 3000], 4: [4, 40, 400, 4000]})

注意defaultdict()只是内置dict类的子类,因此您可以将其与普通词典一样对待。

如果您不想使用任何库,也可以选择dict.setdefault()

t = ((1,1),(1,10),(1,100),(1,1000),(2,2),(2,20),(2,200),(2,2000),(3,3), 
     (3,30),(3,300),(3,3000),(4,4),(4,40),(4,400),(4,4000))

d = {}
for x, y in t:
    d.setdefault(x, []).append(y)

print(d)
# {1: [1, 10, 100, 1000], 2: [2, 20, 200, 2000], 3: [3, 30, 300, 3000], 4: [4, 40, 400, 4000]}
相关问题