Given a dictionary, assign each key, values after reverting the values of dictionary.
# Define a dictionary with key-value pairs my_dict = {'apple': 'red', 'banana': 'yellow', 'grape': 'purple'} # Create a new dictionary to hold the reversed key-value pairs reversed_dict = {} # Loop through each key-value pair in the original dictionary for key, value in my_dict.items(): # Assign the reversed value to the new dictionary using the original key reversed_dict[key] = value[::-1] # Print the original and reversed dictionaries print('Original Dictionary:', my_dict) print('Reversed Dictionary:', reversed_dict)
In this program, we first define a dictionary called my_dict
with some initial key-value pairs. We then create a new dictionary called reversed_dict
to hold the reversed key-value pairs.
Next, we loop through each key-value pair in the original dictionary using the .items()
method. For each key-value pair, we assign the reversed value to the new dictionary using the original key. We reverse the value using Python's string slicing notation [::-1]
.
Finally, we print both the original and reversed dictionaries to the console using Python's built-in print()
function.
This program should output the following:
Original Dictionary: {'apple': 'red', 'banana': 'yellow', 'grape': 'purple'} Reversed Dictionary: {'apple': 'der', 'banana': 'wolley', 'grape': 'elprup'}
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.