我寫了下面的代碼來打印一個大小寫字母字典,其值可以被一個整數移位。它只會返回一個條目(例如{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
你不斷用一個新的一次性字典替換你的字典。 – user2357112