用于交换字典项位置的Python程序
给定一个字典,任务是编写一个Python程序来交换字典项的位置。下面给出的代码采用两个索引和这些索引的交换值。
Input : test_dict = {‘Gfg’ : 4, ‘is’ : 1, ‘best’ : 8, ‘for’ : 10, ‘geeks’ : 9}, i, j = 1, 3
Output : {‘Gfg’: 4, ‘for’: 10, ‘best’: 8, ‘is’: 1, ‘geeks’: 9}
Explanation : (for : 10) and (is : 1) swapped order.
Input : test_dict = {‘Gfg’ : 4, ‘is’ : 1, ‘best’ : 8, ‘for’ : 10, ‘geeks’ : 9}, i, j = 2, 3
Output : {‘Gfg’: 4, ‘is’: 1, ‘for’: 10, ‘best’: 8, ‘geeks’: 9}
Explanation : (for : 10) and (best : 8) swapped order.
方法:使用items()和dict()
此任务分 3 个步骤完成:
- 第一个字典转换为元组形式的等效键值对,
- 下一个交换操作以 Pythonic 的方式执行。
- 最后,元组列表以所需的格式转换回字典。
例子:
Python3
# initializing dictionary
test_dict = {'Gfg': 4, 'is': 1, 'best': 8, 'for': 10, 'geeks': 9}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing swap indices
i, j = 1, 3
# conversion to tuples
tups = list(test_dict.items())
# swapping by indices
tups[i], tups[j] = tups[j], tups[i]
# converting back
res = dict(tups)
# printing result
print("The swapped dictionary : " + str(res))
输出:
The original dictionary is : {‘Gfg’: 4, ‘is’: 1, ‘best’: 8, ‘for’: 10, ‘geeks’: 9}
The swapped dictionary : {‘Gfg’: 4, ‘for’: 10, ‘best’: 8, ‘is’: 1, ‘geeks’: 9}