1

Dictionary I am starting with is:

s={'A' : 'A', 'B' : 'B', 'C' : 'C'} 

Dictionary I want to end up with is:

{'A' : 'B', 'B' : 'C', 'C' : 'A'}.

The only thing I know is how to get random letters instead of the one I have on some particular position, but in this problem I have to shift key's values by n=1.

I have tried to define n by which values are shifted but I end up with an error.

import string
dictionary = dict.fromkeys(string.ascii_lowercase, 0)

def shift(dictionary,s)
    s2=' '
    for c in s:
          n=ord(c) - 65
          n=+=1
          n%=26
          s2+=chr(n+65)
    return s2
pault
  • 41,343
  • 15
  • 107
  • 149
  • 2
    What version of python? Dictionaries are [not ordered before version 3.6](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6/39980744). Are you relying on sorting the keys by alphabetical order? – pault Apr 03 '19 at 17:18
  • 3.7. I want to move each key to the next –  Apr 03 '19 at 17:24
  • how do you define "next". Is it by insertion order? Is it lexicographical order? – pault Apr 03 '19 at 17:25
  • I have a strong suspicion that this is an [XY problem](http://xyproblem.info) and what you're actually looking for is `dict(zip(string.ascii_uppercase, string.ascii_uppercase[1:] + string.ascii_uppercase[0]))` – pault Apr 03 '19 at 17:39

2 Answers2

2

If you're using python 3.6+, then try this :

from collections import deque
s={'A' : 'A', 'B' : 'B', 'C' : 'C'}
rotated_values = deque(s.values())
rotated_values.rotate(-1)
new_s = {k:v for k,v in zip(s, rotated_values)}

OUTPUT :

{'A': 'B', 'B': 'C', 'C': 'A'}
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
0

You should be using OrderedDict's to ensure that your dictionary retains it's ordering when iterating.

from collections import OrderedDict
input_dictionary = OrderedDict(A="A", B="B", C="C")
values = list(input_dictionary.values())
for index, key in enumerate(iter(input_dictionary.keys())):
    new_value_index = (index + 1) % len(values)
    input_dictionary[key] = values[new_value_index]
print(input_dictionary)

Which gives you OrderedDict([('A', 'B'), ('B', 'C'), ('C', 'A')])

Hope that helps

OsmosisJonesLoL
  • 244
  • 1
  • 4