![]() |
VOOZH | about |
Sometimes, while working with Python dictionaries, we can have a problem in which we have keys mapped with values, where keys represent list index where value has to be placed. This kind of problem can have application in all data domains such as web development. Let's discuss certain ways in which this task can be performed.
Input : test_dict = { 1 : 'Gfg', 3 : 'is', 5 : 'Best' }
Output : [0, 'Gfg', 0, 'is', 0, 'Best', 0, 0, 0, 0, 0]Input : test_dict = { 2 : 'Gfg', 6 : 'Best' }
Output : [0, 0, 'Gfg', 0, 0, 0, 'Best', 0, 0, 0, 0]
Method #1: Using list comprehension + keys() The combination of above functions can be used to solve this problem. In this, we perform the task of assigning values to list checking for index, by extracting keys of dictionary for lookup.
The original dictionary is : {2: 'Gfg', 4: 'is', 6: 'Best'}
The converted list : [0, 0, 'Gfg', 0, 'is', 0, 'Best', 0, 0, 0]Time Complexity: O(n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2: Using list comprehension + get() The combination of above functions can be used to solve this problem. In this, we extract element using get(), so as to assign the default values harnessing default value initializing property of get().
The original dictionary is : {2: 'Gfg', 4: 'is', 6: 'Best'}
The converted list : [0, 0, 'Gfg', 0, 'is', 0, 'Best', 0, 0, 0]Method #3 : Using * operator and insert() method
The original dictionary is : {2: 'Gfg', 4: 'is', 6: 'Best'}
The converted list : [0, 0, 'Gfg', 0, 'is', 0, 'Best', 0, 0, 0, 0, 0, 0]Time Complexity : O(N)
Auxiliary Space : O(N)