2017-08-29 57 views
1

我有两个字典,一个在代码的主体和一个输入。我想比较两个字典,如果键是相同的,我想要乘以和打印这些值。以下是我迄今为止编写的代码。Python字典:如果键是相同的乘法值

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 

我真的很感激任何帮助y OU可以给我,谢谢你提前:)

+1

为了测试,如果在dict中使用'dict_a'中的单词。 'split'已经返回一个字符串列表,所以不需要'map'。 – Daniel

+0

好的,谢谢! –

回答

1

您应该使用字典,理解,而不是列表理解:

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

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

所以:

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

接下来的问题是关于你正在试图调用列表,它是不可调用的! 如果你想遍历列表(它的目的地是字典,没有列出但我以前解释),用途:

for word, number in dict_y.items(): 

更多关于字典,谱曲,看那个文档:https://www.python.org/dev/peps/pep-0274/

+0

是的我的意思是,只是我试图写得很快,我忘了那件重要的事情,无论如何感谢您注意 – dannyxn

+0

现在错误:prod = dict_y [编号] * dict_a [编号] TypeError:'set'对象是不可取代的。 .. –

+0

是啊对不起,我已经改变了他们,他们应该是prod dict_a和dict_y –

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中保留订单使用。

+0

非常感谢你,它现在完美的工作,真的很感激 –

+0

@ConorBradley没什么。你能接受我的回答吗? – sKwa