views:

69

answers:

1

I have a dictionary with several values that I want to keep constant, but I need to rotate them throughout the different keys. Is there a built in function or external library that would be able to do this or would I be better off just writing the entire thing myself?

Example of what I am trying to do:

>>> firstdict = {'a':'a','b':'b','c':'c'}  
>>> firstdict.dorotatemethod()  
>>> firstdict  
{'a':'b','b':'c','c':'a'}  
>>>

I does not have to be in order, I just need the values to be associated to a different key each time.

+7  A: 
>>> from itertools import izip
>>> def rotateItems(dictionary):
...   if dictionary:
...     keys = dictionary.iterkeys()
...     values = dictionary.itervalues()
...     firstkey = next(keys)
...     dictionary = dict(izip(keys, values))
...     dictionary[firstkey] = next(values)
...   return dictionary
...
>>> firstdict
{'a': 'a', 'c': 'c', 'b': 'b'}
>>> rotateItems(firstdict)
{'a': 'b', 'c': 'a', 'b': 'c'}
KennyTM