The Wayback Machine - https://web.archive.org/web/20240915181042/https://www.geeksforgeeks.org/python-convert-two-lists-into-a-dictionary/
Open In App

Python | Convert two lists into a dictionary

Last Updated : 13 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 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 this task can be performed. Convert Lists to Nested D
5 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), ("akhil", 25), ("ashish", 30)] Output : {'akash': [
6 min read
Python | Convert dictionary object into string
The dictionary is an important container and is used almost in every code of day-to-day programming as well as web development with Python. The more it is used, the more is the requirement to master it and hence it's necessary to learn about them. Input: { "testname" : "akshat","test2name" : "manjeet","test3name" : "nikhil"}Output: {"testname": "ak
3 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. Below are some ways to achieve the above task. I
8 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 Dictionary into Pandas DataframeBelow are the methods th
4 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 dictionary into NumPy array but before applying th
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 can be used as keys, which means we cannot use a d
6 min read
Python - Unique value keys in a dictionary with lists as values
Sometimes, while working with Python dictionaries, we can have problem in which we need to extract keys with values that are unique (there should be at least one item not present in other lists), i.e doesn't occur in any other key's value lists. This can have applications in data preprocessing. Lets discuss certain ways in which this task can be pe
4 min read
Initializing dictionary with Empty Lists in Python
In Python, it's common to encounter scenarios where you need to store lists in a dictionary. Often, this involves checking if a key exists and then creating a list for that key. However, a more efficient approach is to initialize the dictionary keys with empty lists from the start. Let's explore some methods to accomplish this. How to Initialize a
5 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
Create pandas dataframe from lists using dictionary
Pandas DataFrame is a 2-dimensional labeled data structure like any table with rows and columns. The size and values of the dataframe are mutable, i.e., can be modified. It is the most commonly used pandas object. Creating pandas data-frame from lists using dictionary can be achieved in multiple ways. Let’s discuss different ways to create a DataFr
2 min read
Read a CSV into list of lists in Python
In this article, we are going to see how to read CSV files into a list of lists in Python. Method 1: Using CSV moduleWe can read the CSV files into different data structures like a list, a list of tuples, or a list of dictionaries.We can use other modules like pandas which are mostly used in ML applications and cover scenarios for importing CSV con
2 min read
Turning a Dictionary into XML in Python
XML stands for Extensible Markup Language. XML was designed to be self-descriptive and to store and transport data. XML tags are used to identify, store and organize the data. The basic building block of an XML document is defined by tags. An element has a beginning tag and an ending tag. All elements in an XML are contained in an outermost element
3 min read
Convert Python Nested Lists to Multidimensional NumPy Arrays
Prerequisite: Python List, Numpy ndarray Both lists and NumPy arrays are inter-convertible. Since NumPy is a fast (High-performance) Python library for performing mathematical operations so it is preferred to work on NumPy arrays rather than nested lists. Method 1: Using numpy.array(). Approach : Import numpy package.Initialize the nested list and
2 min read
How to convert lists to XML in Python?
In this article, the task is to convert a given list to XML in Python. But first, let's discuss what is an XML? It could also be terminology that defines a gaggle of rules for encoding documents during a format that's both human-readable and machine-readable. The design goals of XML specialize in simplicity, generality, and usefulness across the we
3 min read
Convert ImmutableMultiDict with duplicate keys to list of lists in Python
In this article, we are going to see how to convert ImmutableMultiDict with duplicate keys to a list of lists using Python. Using Werkzeug Python Werkzeug is a WSGI utility library. WSGI is a protocol or convention that assures that your web application can communicate with the webserver and, more crucially, that web apps can collaborate effectivel
3 min read
Convert Lists to Comma-Separated Strings in Python
Making a comma-separated string from a list of strings consists of combining the elements of the list into a single string with commas between each element. In this article, we will explore three different approaches to make a comma-separated string from a list of strings in Python. Make Comma-Separated String from List of Strings in PythonBelow ar
2 min read
Convert nested Python dictionary to object
Let us see how to convert a given nested dictionary into an object Method 1 : Using the json module. We can solve this particular problem by importing the json module and use a custom object hook in the json.loads() method. C/C++ Code # importing the module import json # declaringa a class class obj: # constructor def __init__(self, dict1): self.__
2 min read
Different ways to convert a Python dictionary to a NumPy array
In this article, we will see Different ways to convert a python dictionary into a Numpy array using NumPy library. 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 of t
3 min read
How to convert NumPy array to dictionary in Python?
The following article explains how to convert numpy array to dictionary in Python. Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, number of dimensions of the array is called rank of the array. A tuple of integers giving the size of the array along each dimension is k
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 session spark = SparkSession.builder.appName('DF_
3 min read
Convert Python Dictionary List to PySpark DataFrame
In this article, we will discuss how to convert Python Dictionary List to Pyspark DataFrame. It can be done in these ways: Using Infer schema.Using Explicit schemaUsing SQL Expression Method 1: Infer schema from the dictionary We will pass the dictionary directly to the createDataFrame() method. Syntax: spark.createDataFrame(data) Example: Python c
3 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 dictionary, where each key corresponds to a diction
3 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 a generator object to a dictionary in Python. Conv
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 converting it into a dictionary. In this article, we will
2 min read
Convert JSON to dictionary in Python
JSON stands for JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the Python JSON package into Python script. The text in JSON is done through quoted-
4 min read
How To Convert Python Dictionary To JSON?
JSON stands for JavaScript Object Notation. It means that a script (executable) file made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which conta
7 min read
Creating a sorted merged list of two unsorted lists in Python
We need to take two lists in Python and merge them into one. Finally, we display the sorted list. Examples: Input : list1 = [25, 18, 9, 41, 26, 31] list2 = [25, 45, 3, 32, 15, 20] Output : [3, 9, 15, 18, 20, 25, 25, 26, 31, 32, 41, 45] Input : list1 = ["suraj", "anand", "gaurav", "aman", "kishore"] list2 = ["rohan", "ram", "mohan", "priya", "komal"
1 min read
Python | Union of two or more Lists
Union of a list means, we must take all the elements from list A and list B (there can be more than two lists) and put them inside a single new list. There are various orders in which we can combine the lists. For e.g., we can maintain the repetition and order or remove the repeated elements in the final list and so on. Examples: Maintained repetit
7 min read
Python | Check if two lists have at-least one element common
Given two lists a, b. Check if two lists have at least one element common in them. Examples: Input : a = [1, 2, 3, 4, 5] b = [5, 6, 7, 8, 9] Output : True Input : a=[1, 2, 3, 4, 5] b=[6, 7, 8, 9] Output : FalseMethod 1: Traversal of List Using traversal in two lists, we can check if there exists one common element at least in them. While traversing
5 min read