【问题标题】:Python Dictionary Returning Only 1 Entry?Python 字典仅返回 1 个条目?
【发布时间】: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


【解决方案1】:

不要将 alpha dict 设置为每次使用时的新条目 dict,而是从空 dict 开始并在所需的键处添加值。

#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 

【讨论】:

    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多