In this post, we are going to understand how to Convert lists of key-value pairs to Python dictionary with examples, Convert lists of the same length to a dictionary or convert lists of different lengths,
1. Convert lists of same length key-value pair to Python Dictionary
In this code snippet, we are converting two lists of the same length into a dictionary using the zip() method.it takes an iterable as an argument and returns an iterator object by joining elements from each iterable (here it is the lists)., We are joining two lists (iterables) using the zip() method, finally, converting them into the dictionary using dict() constructor.
Code Example
#program to Convert lists of key-value pair in Dict
lang_lst = ['C#', 'Go','C++', 'Go','Python' ]
num_lst = [2, 3,4,5,6]
mydict = dict(zip(lang_lst,num_lst))
print('list to dictionary =\n',mydict)
Output
list to dictionary =
{'C#': 2, 'Go': 5, 'C++': 4, 'Python': 6}
2. Convert lists of different length key value pair to dictionary
We are using the zip_longest() function defined in the itertools module as per python doc zip
“Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted. Roughly equivalent to:” Python Docs
- if iterables are uneven in length then the remaining values of iterables are filled by the values assigned to fillvalue parameter of zip_longest(),
- if the value for fillvalue parameter is not passed then the padding will be done with ‘None’.
We are zipping the two iterables by using zip_longest(), converting them into the dictionary by using dict() constructor. As we can see we have not provided any value for fillvalue parmeter, therefore the remaining value of iterable is padded with ‘none’.
Python Program
#program to Convert lists of key-value pair in Dict
from itertools import zip_longest
lang_lst = ['C#', 'Go','C++', 'Go','Python' ]
num_lst = [2, 3,4,5]
mydict = dict(zip_longest(lang_lst,num_lst))
print('list to dictionary =\n',mydict)
Output
list to dictionary =
{'C#': 2, 'Go': 5, 'C++': 4, 'Python': Non
3. Convert lists of alternative key, values pair to a dictionary
To achieve this we are using list slicing, we have a score_list list that contains data for both subject and marks. To convert into the dictionary,
- We will create two lists one is subj_list for key and another is marks_list for values from score_list.
- We will join them using the zip() method, finally convert these into a dictionary using dict() constructor.
Code Example
#program to Convert lists of key-value pair in Dict
score_list = ['Math',100, 'Eng',98,'Sci',99, 'Chemi',100 ]
subj_list = score_list[::2]
marks_list =score_list[1::2]
score_dict = dict(zip(subj_list,marks_list))
print('list to dictionary =\n',score_dict)
Output
list to dictionary =
{'Math': 100, 'Eng': 98, 'Sci': 99, 'Chemi
4. For loop to convert lists of key-values pair to dictionaries
In this code snippet, we are using for loop to convert lists of key-value pairs to the dictionary.
Python Program Example
#program to Convert List to List to dictionaries
score_list = ['Math',100, 'Eng',98,'Sci',99, 'Chemi',100 ]
keys_list = ["subject", "score"]
len = len(score_list)
lst_to_dict = []
for ind in range(0, len, 2):
lst_to_dict.append({keys_list[0]: score_list[ind], keys_list[1] : score_list[ind + 1]})
print('list to dictionary =\n',lst_to_dict)
Output
list to dictionary =
[{'subject': 'Math', 'score': 100}, {'subject': 'Eng', 'score': 98}, {'subject': 'Sci', 'score': 99}, {'subject': 'Chemi', 'score': 100}]
5. Convert lists of key-value to dictionary
In this code snippet, we are using the list and dict comprehension to convert Lists of key-value into dictionaries.
Code Example
#program to Convert List to List of dictionaries
score_list = ['Math',100, 'Eng',98,'Sci',99, 'Chemi',100 ]
keys_list = ["subject", "score"]
len = len(score_list)
lst_to_dict = [{keys_list[0]: score_list[ind], keys_list[1]: score_list[ind+ 1]}for ind in range(0, len, 2)]
print('list to dictionary =\n',lst_to_dict)
Output
list to dictionary =
[{'subject': 'Math', 'score': 100}, {'subject': 'Eng', 'score': 98}, {'subject': 'Sci', 'score': 99}, {'subject': 'Chemi', 'score': 100}]
Summary
We have explored different ways Convert lists of key-value pairs to Python dictionary ey-value in Python Dictionary with code examples. Now by using these methods, We can easily convert lists of key-value in Python Dictionary.
Happy Learning!