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.
Python
# 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.
Python
# 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.
Python
# 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.
Python
# 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.
Python
# 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.
Python
# 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.
Python | Convert two lists into a dictionary – FAQs
How to Add Multiple Lists in Dictionary in Python
To add multiple lists into a dictionary in Python, you can create a dictionary where each key corresponds to one of the lists. Here’s a straightforward way to achieve this:
# Lists to be added
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
# Creating dictionary with lists
my_dict = {'List1': list1, 'List2': list2, 'List3': list3}
print(my_dict)
How to Turn Two Lists into a Dictionary in Python
To convert two lists into a dictionary in Python, where one list contains the keys and the other contains the values, you can use the zip()
function combined with the dict()
constructor:
keys = ['a', 'b', 'c']
values = [1, 2, 3]
# Creating a dictionary from two lists
my_dict = dict(zip(keys, values))
print(my_dict)
How Do You Concatenate Two Lists of Dictionaries in Python
Concatenating two lists of dictionaries can be simply achieved by using the +
operator, which merges the lists together:
list1 = [{'a': 1}, {'b': 2}]
list2 = [{'c': 3}, {'d': 4}]
# Concatenating lists of dictionaries
combined_list = list1 + list2
print(combined_list)
How Do You Add Multiple Items to a Dictionary in Python
You can add multiple items to a dictionary in Python by using the .update()
method of dictionaries, which allows you to pass another dictionary that contains the items you want to add or update:
my_dict = {'a': 1, 'b': 2}
# Adding multiple items
my_dict.update({'c': 3, 'd': 4})
print(my_dict)
How to Make Two Dictionaries into One Dictionary in Python
To merge two dictionaries into one, you can use the update()
method, which will add all items from the second dictionary into the first. In Python 3.5+ you can also use the {**dict1, **dict2}
syntax for a more succinct approach:
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
# Method 1: Using update()
dict1.update(dict2)
# Method 2: Using dictionary unpacking (Python 3.5+)
combined_dict = {**dict1, **dict2}
print(dict1)
print(combined_dict)
Both methods allow you to effectively combine multiple dictionaries into one, expanding your data structure capabilities in Python.
Similar Reads
Python | Convert two lists into a dictionary
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 Li
11 min read
Python | Convert a list of Tuples into Dictionary
Sometimes you might need to convert a tuple to dict object to make it more readable. In this article, we will try to learn how to convert a list of tuples into a dictionary. Here we will find two methods of doing this. Examples: Input : [("akash", 10), ("gaurav", 12), ("anand", 14), ("suraj", 20), (
6 min read
Python | Convert list of tuple into dictionary
Given a list containing all the element and second list of tuple depicting the relation between indices, the task is to output a dictionary showing the relation of every element from the first list to every other element in the list. These type of problems are often encountered in Coding competition
8 min read
Python - Convert Lists to Nested Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to convert lists to nestings, i.e. each list value represents a new nested level. This kind of problem can have applications in many domains including web development. Let's discuss the certain way in which thi
5 min read
Python - Convert list of dictionaries to JSON
In this article, we will discuss how to convert a list of dictionaries to JSON in Python. Python Convert List of Dictionaries to JsonBelow are the ways by which we can convert a list of dictionaries to JSON in Python: Using json.dumps()Using json.dump()Using json.JSONEncoderUsing default ParameterDi
5 min read
How to create a Dictionary in Python
Dictionaries are the fundamental data structure in Python and are very important for Python programmers. They are an unordered collection of data values, used to store data values like a map. Dictionaries are mutable, which means they can be changed. They offer a time complexity of O(1) and have bee
3 min read
Python | Ways to create a dictionary of Lists
Till now, we have seen the ways to create a dictionary in multiple ways and different operations on the key and values in the Python dictionary. Now, let's see different ways of creating a dictionary of lists. Note that the restriction with keys in the Python dictionary is only immutable data types
6 min read
How to convert a MultiDict to nested dictionary using Python
A MultiDict is a dictionary-like object that holds multiple values for the same key, making it a useful data structure for processing forms and query strings. It is a subclass of the Python built-in dictionary and behaves similarly. In some use cases, we may need to convert a MultiDict to a nested d
3 min read
Convert PySpark DataFrame to Dictionary in Python
In this article, we are going to see how to convert the PySpark data frame to the dictionary, where keys are column names and values are column values. Before starting, we will create a sample Dataframe: C/C++ Code # Importing necessary libraries from pyspark.sql import SparkSession # Create a spark
3 min read
Ways to convert string to dictionary
Dictionary is an unordered collection in Python that store data values like a map i.e., key: value pair. In order to convert a String into a dictionary, the stored string must be in such a way that key: value pair can be generated from it. This article demonstrates several ways of converting a strin
4 min read
How To Convert Generator Object To Dictionary In Python
Generators in Python are powerful constructs for handling large datasets efficiently. However, there may be scenarios where you want to convert the output of a generator into a dictionary for easier manipulation and retrieval of data. In this article, we'll explore five different methods to convert
3 min read
How to Compare List of Dictionaries in Python
Comparing a list of dictionaries in Python involves checking if the dictionaries in the list are equal, either entirely or based on specific key-value pairs. This process helps to identify if two lists of dictionaries are identical or have any differences. The simplest approach to compare two lists
3 min read
How to convert a dictionary into a NumPy array?
It's sometimes required to convert a dictionary in Python into a NumPy array and Python provides an efficient method to perform this operation. Converting a dictionary to NumPy array results in an array holding the key-value pairs in the dictionary. Python provides numpy.array() method to convert a
3 min read
Python - Convert dict of list to Pandas dataframe
In this article, we will discuss how to convert a dictionary of lists to a pandas dataframe. Method 1: Using DataFrame.from_dict() We will use the from_dict method. This method will construct DataFrame from dict of array-like or dicts. Syntax: pandas.DataFrame.from_dict(dictionary) where dictionary
2 min read
Python - Write dictionary of list to CSV
In this article, we will discuss the practical implementation of how to write a dictionary of lists to CSV. We can use the csv module for this. The csvwriter file object supports three methods such as csvwriter.writerow(), csvwriter.writerows(), csvwriter.writeheader(). Syntax: csv.writer(csvfile, d
4 min read
How to Convert a List to a DataFrame Row in Python?
In this article, we will discuss how to convert a list to a dataframe row in Python. Method 1: Using T function This is known as the Transpose function, this will convert the list into a row. Here each value is stored in one column. Syntax: pandas.DataFrame(list).T Example: C/C++ Code # import panda
3 min read
Convert Unicode String to Dictionary in Python
Python's versatility shines in its ability to handle diverse data types, with Unicode strings playing a crucial role in managing text data spanning multiple languages and scripts. When faced with a Unicode string and the need to organize it for effective data manipulation, the common task is convert
2 min read
Python | Ways to Convert a 3D list into a 2D list
List is a common type of data structure in Python. While we have used the list and 2d list, the use of 3d list is increasing day by day, mostly in case of web development. Given a 3D list, the task is to convert it into a 2D list. These type of problems are encountered while working on projects or w
3 min read
Python | Convert list of nested dictionary into Pandas dataframe
Given a list of the nested dictionary, write a Python program to create a Pandas dataframe using it. We can convert list of nested dictionary into Pandas DataFrame. Let's understand the stepwise procedure to create a Pandas Dataframe using the list of nested dictionary. Convert Nested List of Dictio
4 min read