【问题标题】:Creating dictionary from a tuple with a for-loop使用 for 循环从元组创建字典
【发布时间】:2020-06-20 17:38:39
【问题描述】:

我有以下元组 tup 并想将其转换为字典。 我找到了似乎有效的代码。但是当我尝试自己的 for 循环时,我得到了一个错误。 有人可以向我解释为什么dict(y,x) 在第一次打印中被允许,但另一个给出了例外?

tup = ((2,'x'),(3,'a'))

#CORRECT CODE
print(dict((y, x) for x, y in tup))                 #output: {'x':2, 'a':3}

#my own for loop, that throws the type error
for x, y in tup:
    print(dict(y,x))                                #output: TypeError dict expected at most 
                                                    #        1 argument, got 2

这两个循环的区别在哪里?

【问题讨论】:

  • 第一个不是dict(y, x),是dict((y, x) for x, y in tup)
  • 你能得到的最接近的是print(dict([(y,x)]))
  • 首先,您不能指望通过反复printing 将任何内容“转换”为其他任何内容。您应该确保您了解在屏幕上显示某些内容与实际进行计算之间的区别。

标签: python python-3.x dictionary for-loop typeerror


【解决方案1】:

(仅供参考)您可以使用的另一种方法

my_dict={}
for a, b in tup: 
    my_dict.setdefault(a,b) 

这里我们使用了字典方法 setdefault() 将第一个参数转换为键,第二个参数转换为字典的值

【讨论】:

    【解决方案2】:

    正确的代码相当于:

    output = {}
    tup = ((2,'x'),(3,'a'))
    
    for x, y in tup:
        output[y] = x
    

    也相当于:

    tup = ((2,'x'),(3,'a'))
    output = {y:x for (x,y) in tup}
    

    它将元组的每个元素的键值对添加到新字典中。

    【讨论】:

      猜你喜欢
      • 2023-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-08
      • 2021-07-25
      • 2019-03-29
      • 1970-01-01
      • 2022-01-13
      相关资源
      最近更新 更多