How to Assign List Item to Dictionary

This tutorial will explain how we can assign the list value to the dictionary key. Sometimes, we need to give list elements as a new key in the dictionary, which can be frequently used in the web development domain. Let's understand the various methods to accomplish this task.

Method - 1: Using zip() with loop

We combine the zip() function and loop to solve the above problem. In this, we combine the list element with the dictionary using zip() and iterate using the for a loop. Let's understand the following example.

Example -

Output:

The original list is : [{'Emp ID': 101, 'Salary': 20000}, {'Emp ID': 102, 'Salary': 30000}]
The modified dictionary : [{'Emp ID': 101, 'Salary': 20000, 'name': 'Peter'}, {'Emp ID': 102, 'Salary': 30000, 'name': 'Gurbaz'}]

Explanation -

In the above code, we have initialized the list contain two dictionary element and printed the original list. Then, we created the new key as name and initialized the name_list that contains names. Then we combined the sample_list and new_list and iterated using for loop. We assigned the name to the new key and appended to the res. We have used the deepcopy() method which constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

Method - 2: Using List Comprehension with zip() function

We can use the list comprehension along with the zip() function to make the above approach shorter. Let's understand the following example.

Example -

Output:

The original list is : [{'Emp ID': 101, 'Salary': 20000}, {'Emp ID': 102, 'Salary': 30000}]
The modified dictionary : [{'Emp ID': 101, 'Salary': 20000, 'name': 'Peter'}, {'Emp ID': 102, 'Salary': 30000, 'name': 'Gurbaz'}]

Method -3: Using for loop and update() method

Let's understand the following example -

Example -

Output:

The original list is : [{'Emp ID': 101, 'Salary': 20000}, {'Emp ID': 102, 'Salary': 30000}]
[{'name': 'Peter'}, {'name': 'Gurbaz'}]
The modified dictionary : [{'Emp ID': 101, 'Salary': 20000, 'name': 'Peter'}, {'Emp ID': 102, 'Salary': 30000, 'name': 'Gurbaz'}]
The modified dictionary : [{'name': 'Peter'}, {'name': 'Gurbaz'}]

Conclusion

In this tutorial, we have explained the various methods to append the list elements to the new key of the dictionary. We have also used the deepcopy() function to append the value to the list.






Latest Courses