+

Python | Compressing two unequal length lists in a dictionary

Since a Python dictionary is an unordered collection of key: value pairs, the result will be printed in an unordered manner.

Method # 1: Using itertools ()

# Python code for demonstration
# return the sum of the dictionary values ​​
# with the same keys in the dictionary list

 

from itertools import cycle

 
# Initializing dictionary list

ini_lis1 = [ `a` , `b` , ` c` , `d` , ` e` ]

ini_lis2 = [ 1 , 2 , 3 ]

  
# loop if the length is shorter

result = dict ( zip (ini_lis1, cycle (ini_lis2)))

 
# print the resulting dictionary

print  ( "resultant dictionary:" , str (result))

Exit :

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

Method # 2: Using Dictation

# Python code for demo
# return the sum of the dictionary values ​​
# with the same keys in the dictionary list

 

from itertools import cycle

 
# Initializing dictionary list

ini_lis1 = [ `a` , `b` , `c` , ` d` , `e` ]

ini_lis2 = [ 1 , 2 , 3 ]

 
# loop if the length is shorter

result = {v: ini_lis2 [i % len (ini_lis2)] 

for i, v in enumerate (ini_lis1)}

  

print ( " resultant dictionary: " , str (result))

Exit:

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

Method # 3: Using deque ()

# Python code for demonstration
# return the sum of the dictionary values ​​
# with the same keys in the dictionary list

  

from collections import deque

 
# Dictionary initializing list

ini_lis1 = [ `a` , ` b` , `c` , ` d` , `e` ]

ini_lis2 = deque ([ 1 , 2 , 3 ])

  
# loop if the length is shorter

result = {}

for letter in ini_lis1:

number = ini_lis2.popleft ()

result [letter] = number

ini_lis2.append (number)

 

print ( "resultant dictionary:" , str (result ))

Exit:

 resultant dictionary: {`c`: 3,` d`: 1, `b`: 2,` e`: 2, `a`: 1} 
Get Solution for free from DataCamp guru