【问题标题】:Can not convert Tuple of Tuple to Dictionary无法将元组的元组转换为字典
【发布时间】:2018-12-11 05:01:48
【问题描述】:

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

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}

【问题讨论】:

  • 您认为字典中有多个具有相同键的条目有意义吗?
  • 它想知道是否有办法转换它。

标签: python-3.x dictionary tuples


【解决方案1】:

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]}

【讨论】:

    猜你喜欢
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多