Here is a program in Python to swap the positions of two items in a dictionary:
def swap_items(dictionary, key1, key2): temp = dictionary[key1] dictionary[key1] = dictionary[key2] dictionary[key2] = temp return dictionary my_dict = {'A': 1, 'B': 2, 'C': 3} print("Original Dictionary: ", my_dict) key1 = 'A' key2 = 'C' my_dict = swap_items(my_dict, key1, key2) print("Dictionary after swapping: ", my_dict)
In this program, we define a function swap_items()
that takes a dictionary and two keys as input. The function swaps the values of the two keys in the dictionary using a temporary variable.
We create a dictionary my_dict
and store some key-value pairs in it. Then, we call the swap_items()
function, passing the dictionary and the two keys to be swapped as arguments. The function returns the updated dictionary after swapping the positions of the two items.
Finally, we print the original dictionary and the updated dictionary after swapping the positions of the two items.
This program can be useful if you want to change the order of items in a dictionary or manipulate the values in a dictionary based on some conditions.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.