convert keys to values in python 1

convert keys to values in python

old_dict = {'A': 67, 'B': 23, 'C': 45, 'D': 56, 'E': 12, 'F': 69, 'G': 67, 'H': 23} 
new_dict = dict([(value, key) for key, value in old_dict.items()])
for i in new_dict: 
    print(i, " :  ", new_dict[i])

Here is what the above code is Doing:
1. We are using a dictionary comprehension to create a new dictionary.
2. The new dictionary is created by swapping the keys and values of the old dictionary.
3. We are iterating over the new dictionary and printing the keys and values.

Similar Posts