Python – Assign list items to Dictionary

Sometimes, while working with Python dictionaries, we can have a problem in which we need to assign list elements as a new key in dictionary. This task can occur in web development domain. Lets discuss certain ways in which this task can be performed.

Method #1 : Using zip() + loop
The combination of above functions can be used to solve this problem. In this, we combine list elements with dictionary using zip() and loop is used to combine iteration logic.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Assign list items to Dictionary
# Using zip() + loop
  
# initializing list
test_list = [{'Gfg' 1, 'id' : 2 }, 
             {'Gfg' 4, 'id' : 4 }]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing key 
new_key = 'best'
  
# initializing list 
add_list = [12, 2]
  
# Assign list items to Dictionary
# Using zip() + loop
res = []
for sub, val in zip(test_list, add_list):
    sub[new_key] = val
    res.append(sub)
      
# printing result 
print("The modified dictionary : " + str(res)) 

chevron_right


Output :

The original list is : [{‘Gfg’: 1, ‘id’: 2}, {‘Gfg’: 4, ‘id’: 4}]
The modified dictionary : [{‘best’: 12, ‘Gfg’: 1, ‘id’: 2}, {‘best’: 2, ‘Gfg’: 4, ‘id’: 4}]

 



Method #2 : Using list comprehension + zip()
The combination of above functions can be used to solve this problem. In this, we perform the iteration of elements using list comprehension and hence a shorthand.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Assign list items to Dictionary
# Using list comprehension + zip()
  
# initializing list
test_list = [{'Gfg' 1, 'id' : 2 }, 
             {'Gfg' 4, 'id' : 4 }]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing key 
new_key = 'best'
  
# initializing list 
add_list = [12, 2]
  
# Assign list items to Dictionary
# Using list comprehension + zip()
res = [{**sub, new_key : ele} for sub, ele in zip(test_list, add_list)]
  
# printing result 
print("The modified dictionary : " + str(res)) 

chevron_right


Output :

The original list is : [{‘Gfg’: 1, ‘id’: 2}, {‘Gfg’: 4, ‘id’: 4}]
The modified dictionary : [{‘best’: 12, ‘Gfg’: 1, ‘id’: 2}, {‘best’: 2, ‘Gfg’: 4, ‘id’: 4}]




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.