![]() |
VOOZH | about |
Given two lists of possibly unequal lengths, the task is to zip two lists in a dictionary such that the list with shorter length will repeat itself. Since the dictionary in Python is an unordered collection of key:value pairs, the result will be printed on unordered fashion.
Method #1: Using itertools()
resultant dictionary : {'b': 2, 'd': 1, 'c': 3, 'e': 2, 'a': 1}Method #2: Using dict comprehension
resultant dictionary : {'d': 1, 'c': 3, 'e': 2, 'b': 2, 'a': 1}Method #3: Using deque()
resultant dictionary : {'c': 3, 'd': 1, 'b': 2, 'e': 2, 'a': 1}Method 4: Using a for loop and a default dictionary.
('Resultant dictionary:', "{'a': 1, 'c': 3, 'b': 2, 'e': 2, 'd': 1}")Time complexity: O(n), where n is the length of the longest list (in this case, n = 5).
Auxiliary space: O(n), where n is the number of unique keys in the dictionary. In the worst case, each key has a different value and therefore each key-value pair needs to be stored in the dictionary.
Method #5: Using defaultdict
- A defaultdict is a subclass of the built-in dictionary class. It overrides one method, missing(), which takes a key argument and returns a default value if the key is not present in the dictionary.
- In this case, we can use a defaultdict to automatically create a new key-value pair with a default value of 0 when we encounter a new key.
- We can then simply add the values to the corresponding keys.
resultant dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 1, 'e': 2}Time Complexity: O(n), where n is the length of the list of keys (ini_lis1).
Auxiliary Space: O(n)
Method #6: Using zip() and dict()
resultant dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 1, 'e': 2}Time Complexity: O(n), where n is the length of the list of keys (ini_lis1).
Auxiliary Space: O(n)