简体   繁体   中英

Shift dictionary values and swap them but not randomly

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

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'}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM