旋转字典的值 [英] Rotate values of a dictionary
问题描述
输入:- {34:'苹果',65:'球',32:'猫',78:'狗'}
输出:- {34:'dog',65:'apple',32:'ball',78:'cat'}
我想出了以下方法,但是有没有更快的方法来执行此任务?
I have come up with the following approach but is there any faster way to perform this task?
def rotate_values(my_dict):
keys_list = list(my_dict.keys())
values_list = list(my_dict.values())
values_list.insert(0, values_list.pop())
my_dict = dict(zip(keys_list, values_list))
return my_dict
推荐答案
您的方法是线性的,您无法改进它,因为您必须重新绑定每个键。但是,您不必将密钥转换为列表( zip
可以与任何可迭代对象一起使用),并且应该使用 deque
进行旋转,因为它支持 O(1)
在两端进行操作,从而实现恒定的时间轮换:
Your approach is linear, which you cannot improve as you have to rebind each key. You do not, however, have to transform the keys to a list (zip
will work with any iterable), and you should use a deque
for the rotation as it supports O(1)
operations on both ends and thus constant time rotation:
from collections import deque
def rotate_values(my_dict):
# no need to cast the keys to list
values_deque = deque(my_dict.values())
values_deque.rotate(1)
return dict(zip(my_dict.keys(), values_deque))
请记住,此过程不是确定性的,因为 dict
是无序的。重复 len(my_dict)
次不一定会产生原始图像。
Keep in mind that this process is not deterministic as dicts
are unordered. Repeating it len(my_dict)
times will not necessarily produce the original.
这篇关于旋转字典的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!