📜  Python – 为连续的值键重新排列字典

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

Python – 为连续的值键重新排列字典

有时,在使用Python字典时,我们可能会遇到一个问题,即我们需要重新排列字典键,以便一个值后跟字典中的相同键。这个问题可以应用于竞争性编程算法和图问题。让我们讨论可以执行此任务的某些方式。

方法#1:使用循环+键()
上述功能的组合可以用来解决这个问题。在此,我们使用 keys() 提取字典键并迭代直到我们找到相等键成功的值。

Python3
# Python3 code to demonstrate working of
# Rearrange dictionary for consecutive value-keys
# Using loop + keys()
 
# initializing dictionary
test_dict = {1 : 3, 4 : 5, 3 : 4, 5 : 6}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Rearrange dictionary for consecutive value-keys
# Using loop + keys()
temp = list(test_dict.keys())[0]
res = {}
while len(test_dict) > len(res):
    res[temp] = temp = test_dict[temp]
 
# printing result
print("The rearranged dictionary : " + str(res))


Python3
# Python3 code to demonstrate working of
# Rearrange dictionary for consecutive value-keys
# Using dictionary comprehension + accumulate()
from itertools import accumulate
 
# initializing dictionary
test_dict = {1 : 3, 4 : 5, 3 : 4, 5 : 6}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Rearrange dictionary for consecutive value-keys
# Using dictionary comprehension + accumulate()
res = {key : test_dict[key] for key in accumulate(test_dict,
                              lambda key, x :test_dict[key])}
 
# printing result
print("The rearranged dictionary : " + str(res))


输出 :
The original dictionary : {1: 3, 4: 5, 3: 4, 5: 6}
The rearranged dictionary : {1: 3, 3: 4, 4: 5, 5: 6}


方法#2:使用字典理解+累加()
上述功能的组合可以用来解决这个问题。在此,我们使用累积执行配对任务,并使用字典理解重新排列新字典。

Python3

# Python3 code to demonstrate working of
# Rearrange dictionary for consecutive value-keys
# Using dictionary comprehension + accumulate()
from itertools import accumulate
 
# initializing dictionary
test_dict = {1 : 3, 4 : 5, 3 : 4, 5 : 6}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Rearrange dictionary for consecutive value-keys
# Using dictionary comprehension + accumulate()
res = {key : test_dict[key] for key in accumulate(test_dict,
                              lambda key, x :test_dict[key])}
 
# printing result
print("The rearranged dictionary : " + str(res))
输出 :
The original dictionary : {1: 3, 4: 5, 3: 4, 5: 6}
The rearranged dictionary : {1: 3, 3: 4, 4: 5, 5: 6}