![]() |
VOOZH | about |
Interconversions are always required while coding in Python, also because of expansion of Python as a prime language in the field of Data Science. This article discusses yet another problem that converts to dictionary and assigns keys as first pair elements as tuple and rest as it’s value. Let’s discuss certain ways in which this can be performed.
Method #1: Using dictionary comprehension This problem can be solved using a shorthand made using dictionary comprehension which performs the classic Naive method of loops in single line inside a dictionary.
The original list : [('Nikhil', 21, 'JIIT'), ('Akash', 22, 'JIIT'), ('Akshat', 22, 'JIIT')]
The dictionary after conversion : {('Akash', 22): ('JIIT', ), ('Akshat', 22): ('JIIT', ), ('Nikhil', 21): ('JIIT', )}Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary space: O(n), where n is the number of tuples in the list.
Method #2: Using dict() + dictionary comprehension Performs task similar to the above method, just the difference comes in the way of creation of dictionary. In the above method, dictionary is created using comprehension, here dict function is used for creation of a dictionary.
The original list : [('Nikhil', 21, 'JIIT'), ('Akash', 22, 'JIIT'), ('Akshat', 22, 'JIIT')]
The dictionary after conversion : {('Akash', 22): ('JIIT', ), ('Akshat', 22): ('JIIT', ), ('Nikhil', 21): ('JIIT', )}The time complexity of this code is O(n), where n is the length of the input list.
The auxiliary space complexity of this code is O(n), where n is the length of the input list.
Method #3: Using the zip() function
First creates a list of keys by iterating over the tuples in the original list and selecting the first two elements of each tuple. Then, it creates a list of values by iterating over the tuples again and selecting everything after the first two elements of each tuple. Finally, it uses the zip() function to combine the keys and values lists into a single list of (key, value) tuples, and passes that list to the dict() function to create the resulting dictionary.
{('Nikhil', 21): ('JIIT',), ('Akash', 22): ('JIIT',), ('Akshat', 22): ('JIIT',)}Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(n), where n is the length of the input list test_list.
Method #4: Using a for loop and the setdefault() method
The original list : [('Nikhil', 21, 'JIIT'), ('Akash', 22, 'JIIT'), ('Akshat', 22, 'JIIT')]
The dictionary after conversion : {('Nikhil', 21): ['JIIT'], ('Akash', 22): ['JIIT'], ('Akshat', 22): ['JIIT']}
Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(n), where n is the length of the input list test_list.