VOOZH about

URL: https://www.geeksforgeeks.org/python/python-zipping-two-unequal-length-list-in-dictionary/

⇱ Python | Zipping two unequal length list in dictionary - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python | Zipping two unequal length list in dictionary

Last Updated : 26 Apr, 2023

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()

Output:
resultant dictionary : {'b': 2, 'd': 1, 'c': 3, 'e': 2, 'a': 1}

Method #2: Using dict comprehension 

Output:
resultant dictionary : {'d': 1, 'c': 3, 'e': 2, 'b': 2, 'a': 1}

Method #3: Using deque() 

Output:
resultant dictionary : {'c': 3, 'd': 1, 'b': 2, 'e': 2, 'a': 1}

Method 4: Using a for loop and a default dictionary. 

  1. Import defaultdict from the collections module.
  2. Create an empty defaultdict named 'result_dict' with int as the default value type.
  3. Loop through the 'ini_lis1' and 'ini_lis2' simultaneously using the built-in zip() function.
  4. For each iteration, add the value in 'ini_lis2' to the corresponding key in 'result_dict'.
  5. Return 'result_dict'.

Output
('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

  1. 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. 
  2. 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. 
  3. We can then simply add the values to the corresponding keys.

Output
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()


Output
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)

Comment