Skip to content

Invert a dictionary in Python


Inverting a dictionary basically means keys and values are swapped i.e keys become values and values become keys.

dictionary = {'class': 'X', 'age': 16, 'score': 88, 'name': 'Anand', 'sex': 'Male'}

print({ value: key for key, value in dictionary.items() })

#{16: 'age', 88: 'score', 'Male': 'sex', 'Anand': 'name', 'X': 'class'}
See also  Rank sort a list of dictionaries based on a value in Python

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.