2017-08-29 91 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

相關問題