在python中旋转字典键

2024-09-29 21:32:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字典,其中有几个值我想保持不变,但我需要在不同的键之间旋转它们。是否有一个内置的函数或外部库可以做到这一点,还是我自己编写整个程序会更好?在

我想做的事情的例子:

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

我不必按顺序排列,我只需要每次将值关联到不同的键。在


Tags: 函数程序字典事情内置例子将值firstdict
1条回答
网友
1楼 · 发布于 2024-09-29 21:32:42
>>> 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'}

相关问题 更多 >

    热门问题