在python中旋转字典键
我有一个字典,里面有几个我想保持不变的值,但是我需要在不同的键中旋转它们。是否有一个内置函数或外部库能够做到这一点,或者我自己写整个东西会更好 我正在尝试做的示例:在python中旋转字典键,python,dictionary,rotation,key,Python,Dictionary,Rotation,Key,我有一个字典,里面有几个我想保持不变的值,但是我需要在不同的键中旋转它们。是否有一个内置函数或外部库能够做到这一点,或者我自己写整个东西会更好 我正在尝试做的示例: >>> firstdict = {'a':'a','b':'b','c':'c'} >>> firstdict.dorotatemethod() >>> firstdict {'a':'b','b':'c','c':'a'} >>> 我不必按顺
>>> firstdict = {'a':'a','b':'b','c':'c'}
>>> firstdict.dorotatemethod()
>>> firstdict
{'a':'b','b':'c','c':'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'}