Python词典:如果键相同则乘以值

时间:2017-08-29 22:04:51

标签: python python-3.x dictionary

我有两个词典,一个在主体代码中,一个在输入中。我想比较两个词典,如果键是相同的,我想乘以并打印值。下面是我到目前为止编写的代码。

dict_a = {
    'r':100,
    'y':110,
    'a':210
    }

print('Enter The Number Of Items You Wish To Input')

n = int(input())
dict_y={}
print('Enter your dictionary')
dict_y = [ map(str, input().split()) for x in range(n)]

total = []

for word, number in dict_y:
     if word in dict_a.keys():
           prod = dict_y[number] * dict_a[number]
           print(prod)

我一直收到同样的错误,并且不知道原因:

           prod = dict_a[number] * dict_y[number]
           TypeError: 'set' object is unsubscriptable

示例输入为:

r 10
y 5
a 20

然后,所需的输出将是

1000
550
210

我真的很感激你能给我的任何帮助,谢谢你提前:))

2 个答案:

答案 0 :(得分:1)

你应该使用dict-comprehension而不是list-comprehension:

dict_y = [ map(str, input().split()) for x in range(n)]

将“[...]”替换为“{...}”。

所以:

dict_y = {map(str, input().split()) for x in range(n)}

接下来的问题是你试图调用list,它不可调用! 如果你想迭代列表(它的目的地是dict,而不是列表,但我之前解释过),请使用:

for word, number in dict_y.items():

有关dict-comps的更多信息,请查看该文档:https://www.python.org/dev/peps/pep-0274/

答案 1 :(得分:0)

试试这个:

...
dict_y = dict((map(str, input().split())) for x in range(n))
...
for key in dict_y:
    if key in dict_a:
        print(int(dict_a[key]) * int(dict_y[key]))
...

dict中的订单未保留。如果您需要在OrderedDict

中保留订单使用