![]() |
VOOZH | about |
Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. Let's discuss a few ways to invert mapping of a dictionary.
Method #1: Using Dictionary Comprehension.
initial dictionary : {201: 'ball', 101: 'akshat'}
inverse mapped dictionary : {'ball': 201, 'akshat': 101}Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), to store the keys and values in dictionary.
Method #2: Using dict.keys() and dict.values()
initial dictionary : {201: 'ball', 101: 'akshat'}
inverse mapped dictionary : {'ball': 201, 'akshat': 101}Method #3: Using map() and reversed
initial dictionary : {201: 'ball', 101: 'akshat'}
inverse mapped dictionary : {'akshat': 101, 'ball': 201}Method #4: Using lambda
initial dictionary : {201: 'ball', 101: 'akshat'}
inverse mapped dictionary : {201: 'ball', 101: 'akshat'}The time complexity of this code is O(n), where n is the number of key-value pairs in the dictionary ini_dict. dictionary.
The auxiliary space complexity of this code is O(n), where n is the number of key-value pairs in the dictionary ini_dict.
Approach:
{1: 'a', 2: 'b', 3: 'c'}Time complexity: O(n), where n is the number of key-value pairs in the dictionary
Space complexity: O(n), where n is the number of key-value pairs in the dictionary