📜  Python - 按 K 旋转字典

📅  最后修改于: 2022-05-13 01:55:11.826000             🧑  作者: Mango

Python - 按 K 旋转字典

给定一个字典,通过将字典键右旋转 K 来执行其重新排序。

例子:

方法 #1:使用列表理解+ items() +字典理解

在此,我们执行将字典转换为元组列表的任务,然后执行列表旋转,发布后,结果再次转换为字典以获得结果键旋转。

Python3
# Python3 code to demonstrate working of
# Rotate dictionary by K
# Using list comprehension + items() + dictionary comprehension
  
# initializing dictionary
test_dict = {1: 6, 8: 1, 9: 3, 10: 8, 12: 6, 4: 9}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K
K = 2
  
# converting to tuples list
test_dict = list(test_dict.items())
  
# performing rotate
res = [test_dict[(i - K) % len(test_dict)]
       for i, x in enumerate(test_dict)]
  
# reconverting to dictionary
res = {sub[0]: sub[1] for sub in res}
  
# printing result
print("The required result : " + str(res))


Python3
# Python3 code to demonstrate working of
# Rotate dictionary by K
# Using deque.rotate() + dictionary comprehension + items()
from collections import deque
  
# initializing dictionary
test_dict = {1: 6, 8: 1, 9: 3, 10: 8, 12: 6, 4: 9}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K
K = 2
  
# converting to tuples list
test_dict = list(test_dict.items())
  
# performing rotate
# using deque
test_dict = deque(test_dict)
test_dict.rotate(K)
test_dict = list(test_dict)
  
# reconverting to dictionary
res = {sub[0]: sub[1] for sub in test_dict}
  
# printing result
print("The required result : " + str(res))


输出:

方法#2:使用deque.rotate() + 字典理解 + items()

在此,我们使用 deque.rotate 实用程序执行旋转任务,其余所有功能都以与上述方法类似的方式执行。

蟒蛇3

# Python3 code to demonstrate working of
# Rotate dictionary by K
# Using deque.rotate() + dictionary comprehension + items()
from collections import deque
  
# initializing dictionary
test_dict = {1: 6, 8: 1, 9: 3, 10: 8, 12: 6, 4: 9}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K
K = 2
  
# converting to tuples list
test_dict = list(test_dict.items())
  
# performing rotate
# using deque
test_dict = deque(test_dict)
test_dict.rotate(K)
test_dict = list(test_dict)
  
# reconverting to dictionary
res = {sub[0]: sub[1] for sub in test_dict}
  
# printing result
print("The required result : " + str(res))

输出: