2016-08-01 45 views
1

我寫了下面的代碼來打印一個大小寫字母字典,其值可以被一個整數移位。它只會返回一個條目(例如{Z:z}),即使當我在for循環中使用print語句時,無論轉換如何,我都會看到整個字典按預期打印。任何想到爲什麼它只會返回一個條目將不勝感激?Python字典只返回1條目嗎?

def dictionary(self, shift):  
    ''' 
    For Caesar cipher. 

    shift (integer): the amount by which to shift every letter of the 
    alphabet. 0 <= shift < 26 

    Returns: a dictionary mapping a letter (string) to 
      another letter (string). 
    ''' 

    #create empty dictionary 
    alphaDict = {} 

    #retrieve alphabet in upper and lower case 
    letters = string.ascii_lowercase + string.ascii_uppercase 

    #build dictionary with shift 
    for i in range(len(letters)): 
     if letters[i].islower() == True: 
      alphaDict = {letters[i]: letters[(i + shift) % 26]} 
     else: 
      alphaDict = {letters[i]: letters[((i + shift) % 26) + 26]} 

    return alphaDict 
+3

你不斷用一個新的一次性字典替換你的字典。 – user2357112

回答

2

而不是設置阿爾法字典是一個新的條目字典每次使用後,開始與空字典,並在您需要的鍵添加值。

#build dictionary with shift 
for i in range(len(letters)): 
    if letters[i].islower() == True: 
     alphaDict[letters[i]] = letters[(i + shift) % 26] 
    else: 
     alphaDict[letters[i]] = letters[((i + shift) % 26) + 26] 

return alphaDict 
+0

非常感謝,沒有線索我錯過了! –

2

您正在每個循環創建一個新字典,而不是追加它。你想創建一個新的key - value對字典每個循環。

for i in letters: 
     if i.islower() == True: 
      alphaDict[i] = letters[(letters.index(i) + shift) % 26]} 
     else: 
      alphaDict[i] = letters[((letters.index(i) + shift) % 26) + 26]} 

return alphaDict 
+0

非常感謝您的洞察! –