2

I've written the following code to print an upper/lower case alphabet dictionary whose values can be shifted by an integer. It keeps returning only one entry (e.g., {Z:z}), even though when I use a print statement in the for loop, I see the entire dictionary printed as expected, no matter what the shift. Any thoughts on why it would only return one entry would be greatly appreciated?

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 
NewGuy_IL
  • 51
  • 5

2 Answers2

2

Instead of setting alpha dict to be a new one entry dict with each use, start with an empty dict and add values at the keys you want.

#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 
robot1208
  • 191
  • 1
  • 7
2

You are creating a new dictionary each loop rather than appending it. YOu want to create a new key - value pair for the dictionary each loop.

    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
user3636636
  • 2,409
  • 2
  • 16
  • 31