Python – 在字典中分配反转值
给定一个字典,在还原字典的值后分配每个键值。
Input : {1 : 4, 2 : 5, 3 : 6}
Output : {1 : 6, 2 : 5, 3 : 4}
Explanation : Value order changed, 4, 5, 6 to 6, 5, 4.
Input : {1 : 5, 2 : 5, 3 : 5}
Output : {1 : 5, 2 : 5, 3 : 5}
Explanation : Same values, no visible change.
方法 #1:使用 values() + loop + reversed()
这是可以执行此任务的方式之一。在此,我们使用 reversed() 反转字典中的所有值并重新分配给键。
Python3
# Python3 code to demonstrate working of
# Assign Reversed Values in Dictionary
# Using reversed() + loop + values()
# initializing dictionary
test_dict = {1 : "Gfg", 2 : "is", 3 : "Best"}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# extract values using values()
new_val = list(reversed(list(test_dict.values())))
# reassign new values
res = dict()
cnt = 0
for key in test_dict:
res[key] = new_val[cnt]
cnt += 1
# printing result
print("Reassigned reverse values : " + str(res))
Python3
# Python3 code to demonstrate working of
# Assign Reversed Values in Dictionary
# Using dictionary comprehension + reversed() + values()
# initializing dictionary
test_dict = {1 : "Gfg", 2 : "is", 3 : "Best"}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# extract values using values()
new_val = list(reversed(list(test_dict.values())))
# one-liner dictionary comprehension approach
# enumerate for counter
res = {key : new_val[idx] for idx, key in enumerate(list(test_dict.keys()))}
# printing result
print("Reassigned reverse values : " + str(res))
输出
The original dictionary is : {1: 'Gfg', 2: 'is', 3: 'Best'}
Reassigned reverse values : {1: 'Best', 2: 'is', 3: 'Gfg'}
方法 #2:使用字典理解 + reversed() + values()
上述功能的组合可以用来解决这个问题。在此,我们使用字典理解配方执行重建逆向字典的任务,以实现单线解决方案。
Python3
# Python3 code to demonstrate working of
# Assign Reversed Values in Dictionary
# Using dictionary comprehension + reversed() + values()
# initializing dictionary
test_dict = {1 : "Gfg", 2 : "is", 3 : "Best"}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# extract values using values()
new_val = list(reversed(list(test_dict.values())))
# one-liner dictionary comprehension approach
# enumerate for counter
res = {key : new_val[idx] for idx, key in enumerate(list(test_dict.keys()))}
# printing result
print("Reassigned reverse values : " + str(res))
输出
The original dictionary is : {1: 'Gfg', 2: 'is', 3: 'Best'}
Reassigned reverse values : {1: 'Best', 2: 'is', 3: 'Gfg'}