【发布时间】:2016-12-06 01:28:12
【问题描述】:
我编写了以下代码来打印一个大写/小写字母字典,其值可以移动一个整数。它一直只返回一个条目(例如,{Z:z}),即使当我在 for 循环中使用 print 语句时,我看到整个字典都按预期打印,无论发生什么转变。任何关于为什么它只会返回一个条目的想法将不胜感激?
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
【问题讨论】:
-
你不断用新的单项字典替换你的字典。
标签: python dictionary return caesar-cipher