Open In App

Python | Convert two lists into a dictionary

Improve
Improve
Like Article
Like
Save
Share
Report

Interconversion between data types is usually necessary for real-time applications as certain systems have certain modules that require input in a particular data type. Let’s discuss a simple yet useful utility of conversion of two lists into a key: value pair dictionary in Python

Converting Two Lists into a Dictionary

Python List is a sequence data type that is used to store the collection of data. It is a collection of things, enclosed in [ ] and separated by commas. A Dictionary in Python is a collection of key-value pairs, used to store data values like a map, which, unlike other data types holds only a single value as an element.

Let us see a few methods to convert two lists into a dictionary in Python.

Create Dictionary From Two Lists using Naive Method

The basic method that can be applied to perform this task is the brute force method. It is an intuitive, direct, and straightforward technique of problem-solving in which all the possible ways or all the possible solutions to a given problem are enumerated.

Example:

In this example, we will simply take 2 lists and declare an empty dictionary, and then using a nested for loop on both the lists, assign the key and value from the ‘test_keys’ list and ‘test_values’ list respectively to the dictionary. 

Python3




# Python3 code to demonstrate
# conversion of lists to dictionary
# using naive method
 
# initializing lists
test_keys = ["Rash", "Kil", "Varsha"]
test_values = [1, 4, 5]
 
# Printing original keys-value lists
print("Original key list is : " + str(test_keys))
print("Original value list is : " + str(test_values))
 
# using naive method
# to convert lists to dictionary
res = {}
for key in test_keys:
    for value in test_values:
        res[key] = value
        test_values.remove(value)
        break
 
# Printing resultant dictionary
print("Resultant dictionary is : " + str(res))


Output:

Original key list is : ['Rash', 'Kil', 'Varsha']
Original value list is : [1, 4, 5]
Resultant dictionary is : {'Rash': 1, 'Kil': 4, 'Varsha': 5}

Time complexity: O(n^2), where n is the length of the test_keys list.
Auxiliary Space: O(n), where n is the length of the test_keys list. The space complexity is proportional to the size of the dictionary created in the program, which has n key-value pairs.

Create Dictionary From Two Lists using Dictionary Comprehension 

It is a more concise way to achieve the above method. The dictionary comprehension method offers a faster and time-saving approach by reducing the lines to type. A dictionary comprehension takes the form {key: value for (key, value) in iterable}. 

Example:

In this example, we will pass the key and the value lists to the final dictionary and then use a for loop to insert them into a key-value pair in the final dictionary.

Python3




# Python3 code to demonstrate
# conversion of lists to dictionary
# using dictionary comprehension
 
# initializing lists
test_keys = ["Rash", "Kil", "Varsha"]
test_values = [1, 4, 5]
 
# Printing original keys-value lists
print("Original key list is : " + str(test_keys))
print("Original value list is : " + str(test_values))
 
# using dictionary comprehension
# to convert lists to dictionary
res = {test_keys[i]: test_values[i] for i in range(len(test_keys))}
 
# Printing resultant dictionary
print("Resultant dictionary is : " + str(res))


Output:

Original key list is : ['Rash', 'Kil', 'Varsha']
Original value list is : [1, 4, 5]
Resultant dictionary is : {'Rash': 1, 'Kil': 4, 'Varsha': 5}

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), as the program creates a new dictionary res that can have at most n key-value pairs, where n is the length of the input list.

Create Dictionary From Two Lists using map() method 

We will use the Python map() function to pair the list element with other list elements at the corresponding index in the form of key-value pairs and typecast this tuple list to the dictionary.

Example:

In this example, we will use the map() function to map the elements of the keys and values list into the dictionary.

Python




# Python3 code to demonstrate
# conversion of lists to dictionary
# using dict() + map()
 
# initializing lists
keys = ["Rash", "Kil", "Varsha"]
values = [1, 4, 5]
 
# Printing original keys-value lists
print ("Original key list is : " + str(keys))
print ("Original value list is : " + str(values))
 
# using map and dict type casting
# to convert lists to dictionary
res = dict(map(lambda i,j : (i,j) , keys,values))
 
# Printing resultant dictionary
print ("Resultant dictionary is : " + str(res))


Output:

Original key list is : ['Rash', 'Kil', 'Varsha']
Original value list is : [1, 4, 5]
Resultant dictionary is : {'Rash': 1, 'Kil': 4, 'Varsha': 5}

Time complexity: O(n), where n is the length of the input lists. 
Auxiliary space: O(n), as a new dictionary of size n is created to store the key-value pairs.

Create Dictionary From Two Lists using enumerate()

In this example, the Python enumerate() function is used to loop over the elements in the zip(test_keys, test_values) object, which pairs the elements in the two lists together. The resulting tuples are then added to a list, which is passed as an argument to the dict() function to create the dictionary.

Example:

In this example, we use the enumerate() function to loop over both lists simultaneously, creating a list of Python tuples. The enumerate() function returns a tuple with two values: the index of the current item and the value of the item itself. We use the zip() function to combine the test_keys and test_values lists into a single iterable that we can loop over. Inside the loop, we use tuple unpacking to assign the current key and value to variables named key and value, respectively. We then create a tuple (key, value) and append it to the tuples list. Then we use the dict() function to convert the list of tuples into a dictionary. The dict() function takes an iterable of key-value pairs and returns a dictionary.

Python3




# Python3 code to demonstrate
# conversion of lists to dictionary
# using dict() + map()
 
# initializing lists
test_keys = ["Rash", "Kil", "Varsha"]
test_values = [1, 4, 5]
 
# Printing original keys-value lists
print ("Original key list is : " + str(test_keys))
print ("Original value list is : " + str(test_values))
 
 
# create a list of tuples using enumerate()
tuples = [(key, value)
          for i, (key, value) in enumerate(zip(test_keys, test_values))]
 
# convert list of tuples to dictionary using dict()
res = dict(tuples)
 
print ("Resultant dictionary is : " + str(res))


Output:

Original key list is : ['Rash', 'Kil', 'Varsha']
Original value list is : [1, 4, 5]
Resultant dictionary is : {'Rash': 1, 'Kil': 4, 'Varsha': 5}

Time complexity: O(n), as the algorithm needs to iterate over the elements in the lists and perform some operations on each element.
Auxiliary space: O(n), where n is the length of the lists. This is because the approach involves creating a list of tuples, which has a length equal to the length of the lists. In addition, the approach requires space to store the variables key and value in each iteration of the loop.

Convert two lists into a dictionary using dict() and zip()

This method uses the built-in dict() function to create a dictionary from two lists using the zip() function. The zip() function pairs the elements in the two lists together, and dict() converts the resulting tuples to key-value pairs in a dictionary.

Example:

In this example, we created a dictionary using the dict() function and zip() function, which pairs the elements in the two lists together.

Python3




# initializing lists
test_keys = ["Rash", "Kil", "Varsha"]
test_values = [1, 4, 5]
 
# Printing original keys-value lists
print("Original key list is : " + str(test_keys))
print("Original value list is : " + str(test_values))
 
# using dict() and zip() to convert lists to dictionary
res = dict(zip(test_keys, test_values))
 
# Printing resultant dictionary
print("Resultant dictionary is : " + str(res))


Output:

Original key list is : ['Rash', 'Kil', 'Varsha']
Original value list is : [1, 4, 5]
Resultant dictionary is : {'Rash': 1, 'Kil': 4, 'Varsha': 5}

Time complexity: O(n), where n is the length of the lists. The zip() and dict() functions have a complexity of O(n).
Auxiliary space: O(n), for the resulting dictionary.

Use the fromkeys() method of the dictionary object

Python dictionary fromkeys() function returns the dictionary with key mapped and specific value. It creates a new dictionary from the given sequence with a specific value.

Example:

In this example, we use the fromkeys() method to create a new dictionary with keys from test_keys and set its values to None. Then using a for loop to iterate through each key in result_dict and update its value with the corresponding value from test_values.

Python3




# initializing lists
test_keys = ["Rash", "Kil", "Varsha"]
test_values = [1, 4, 5]
 
# using the fromkeys() method to create a dictionary
result_dict = dict.fromkeys(test_keys)
 
# iterating through the dictionary and updating values
for key, value in zip(result_dict.keys(), test_values):
    result_dict[key] = value
 
# printing the original lists
print("Original key list is : " + str(test_keys))
print("Original value list is : " + str(test_values))
 
print("Resultant dictionary is : " + str(result_dict))


Output:

Original key list is : ['Rash', 'Kil', 'Varsha']
Original value list is : [1, 4, 5]
Resultant dictionary is : {'Rash': 1, 'Kil': 4, 'Varsha': 5}

Time complexity: O(n), where n is the length of the lists, because we iterate through each key in the dictionary once and update its value. 
Auxiliary space: O(n), because we create a dictionary with n keys and values set to None.

Convert two lists into a dictionary using the Itertools module and the groupby() function

Python’s Itertools is a module that provides various functions that work on iterators to produce complex iterators. The groupby() function of itertools module is used to calculate the keys for each element present in iterable. It returns the key and the iterable of grouped items.

Python3




# import itertools
import itertools
 
# initializing lists
test_keys = ["Rash", "Kil", "Varsha"]
test_values = [1, 4, 5]
 
# printing the original lists
print("Original key list is : " + str(test_keys))
print("Original value list is : " + str(test_values))
 
# iterating through the dictionary and updating values
key_value_pairs = zip(test_keys, test_values)
sorted_pairs = sorted(key_value_pairs, key=lambda x: x[0])
grouped_pairs = itertools.groupby(sorted_pairs, key=lambda x: x[0])
res = {key: next(group)[1] for key, group in grouped_pairs}
 
print("Resultant dictionary is : " + str(res))


Output:

Original key list is : ['Rash', 'Kil', 'Varsha']
Original value list is : [1, 4, 5]
Resultant dictionary is : {'Kil': 4, 'Rash': 1, 'Varsha': 5}

Time Complexity: O(n log n), where n is the length of the input lists.
Auxiliary Space: O(n), where n is the length of the input lists. 



Last Updated : 01 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads