我想使用我的字典中的值。也计算 - 但它不起作用

时间:2017-11-14 12:21:45

标签: python python-3.x dictionary

我有以下代码:

mydict = {"test1": (2,3), "test2": (1)}

for key,value in mydict.items():
    mydict[key] = 1/(1+value)
print(mydict)

但是我收到了这个错误:

"TypeError: unsupported operand type(s) for +: 'int' and 'tuple'"

我想要的是这个:

对于包含两个值的test1,我需要以下内容:

1/(a+1) + 1/(b+1) = 0.5833 

a和b是相应键的元组中的值

test1 = 0.5833

类似地,对于test2

1/(a+1) = 1/2 = 0.5

test2 = 0.5

1 个答案:

答案 0 :(得分:1)

要实现这一点,您需要遍历元组。我修改了下面的代码并添加了兴趣点的评论。请告诉我这是否符合预期?

mydict = {"test1": (2,3 ), "test2": ( 1)}

for key,value  in mydict.items():
    # state the value as 0 to allow iterations to be added to together
    mydict[key] = 0

    # we check if it is a integer
    if not isinstance(value, int): 
        #if not an integer we interate through the values
        for x in value:
            # add the value to the total
            mydict[key] += 1/(1+x)

    else:
        mydict[key] = 1/(1+value)
print(mydict)