Python program to assign reversed values in dictionary

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'}

 

Submit Your Programming Assignment Details