Python - 在字典中交换第 i 个和第 j 个键的值
给定一个字典,交换第 i 个和第 j 个索引键的值。
Input : test_dict = {“Gfg”: 2, “is”: 4, “best”: 7, “for”: 9, “geeks”: 10}, i, j = 1, 4
Output : {‘Gfg’: 2, ‘is’: 10, ‘best’: 7, ‘for’: 9, ‘geeks’: 4}
Explanation : Values of “is” and “geeks” swapped.
Input : test_dict = {“Gfg”: 2, “is”: 4, “best”: 7, “for”: 9, “geeks”: 10}, i, j = 1, 2
Output : {‘Gfg’: 2, ‘is’: 7, ‘best’: 4, ‘for’: 9, ‘geeks’: 10}
Explanation : Values of “is” and “best” swapped.
方法 #1:使用循环 + values()
这是可以执行此任务的方法之一。在这里,我们获得所需的交换键的值并在循环中执行所需的交换,这将创建一个新字典。
Python3
# Python3 code to demonstrate working of
# Swap ith and jth key's value in dictionary
# Using loop + values()
# initializing dictionary
test_dict = {"Gfg": 2, "is": 4, "best": 7,
"for": 9, "geeks": 10}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing i, j
i, j = 1, 3
# Extracting keys
vals = list(test_dict.values())
# performing swap
vals[i], vals[j] = vals[j], vals[i]
# setting new values
res = dict()
for idx, key in enumerate(test_dict):
res[key] = vals[idx]
# printing result
print("Required dictionary : " + str(res))
Python3
# Python3 code to demonstrate working of
# Swap ith and jth key's value in dictionary
# Using values() + dictionary comprehension
# initializing dictionary
test_dict = {"Gfg": 2, "is": 4, "best": 7,
"for": 9, "geeks": 10}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing i, j
i, j = 1, 3
# Extracting keys
vals = list(test_dict.values())
# performing swap
vals[i], vals[j] = vals[j], vals[i]
# setting new values
res = {key : vals[idx] for idx, key in enumerate(test_dict)}
# printing result
print("Required dictionary : " + str(res))
输出:
The original dictionary is : {‘Gfg’: 2, ‘is’: 4, ‘best’: 7, ‘for’: 9, ‘geeks’: 10}
Required dictionary : {‘Gfg’: 2, ‘is’: 9, ‘best’: 7, ‘for’: 4, ‘geeks’: 10}
方法#2:使用 values() + 字典理解
这是可以执行此任务的方法之一。这是一种与上面类似的方法,不同之处在于字典分配步骤是使用字典理解来执行的。
蟒蛇3
# Python3 code to demonstrate working of
# Swap ith and jth key's value in dictionary
# Using values() + dictionary comprehension
# initializing dictionary
test_dict = {"Gfg": 2, "is": 4, "best": 7,
"for": 9, "geeks": 10}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing i, j
i, j = 1, 3
# Extracting keys
vals = list(test_dict.values())
# performing swap
vals[i], vals[j] = vals[j], vals[i]
# setting new values
res = {key : vals[idx] for idx, key in enumerate(test_dict)}
# printing result
print("Required dictionary : " + str(res))
输出:
The original dictionary is : {‘Gfg’: 2, ‘is’: 4, ‘best’: 7, ‘for’: 9, ‘geeks’: 10}
Required dictionary : {‘Gfg’: 2, ‘is’: 9, ‘best’: 7, ‘for’: 4, ‘geeks’: 10}