You are currently viewing Convert Two Lists into Dictionary in Python

How to convert two lists into a dictionary in Python or create a dictionary from lists? You can use built-in functions like zip() and dict() or more advanced techniques like dictionary comprehensions and loops to convert two lists into Python dictionary. In this article, we will learn how to convert two lists into a dict object with examples.

Advertisements

1. Quick Examples of Converting Lists into a Dictionary

These code examples will give you a high-level overview of what we will discuss in this article. If you are in hurry this is a good place to start. You can get an idea of how to convert two lists into a dictionary. We will discuss each of the example in detail in later sections.


# Quick examples of converting two lists into a dictionary

# Lists for keys and values
keys_list = ['a', 'b', 'c']
values_list = [1, 2, 3]

# Method 1: Using the zip() function and the dict() constructor
my_dict = dict(zip(keys_list, values_list))
print(my_dict)

# Method 2: Using the enumerate() function and a loop
my_dict = {}
for i, key in enumerate(keys_list):
    my_dict[key] = values_list[i]
print(my_dict)

# Method 3: Using the zip() function and a loop
my_dict = {}
for k, v in zip(keys_list, values_list):
    my_dict[k] = v
print(my_dict)

# Method 4: Using the fromkeys() method and a loop
my_dict = dict.fromkeys(keys_list, None)
for i in range(len(keys_list)):
    my_dict[keys_list[i]] = values_list[i]
print(my_dict)

2. Use zip() to Convert Two Lists to Dictionary

The zip() function in Python is used to combine two lists into a single list of tuples, where the first element of the tuple contains the elements of first list, the second element of the tuple contains the element from second list and pass this as an input to dict() constructor to create a dictionary.

Following is an example of using dict(zip()) to convert two lists into a dictionary.


# Convert two lists into a Dictionary
my_keys = ['a', 'b', 'c']
my_values = [1, 2, 3]

my_dict = dict(zip(my_keys, my_values))
print(my_dict)  

# Output: 
# {'a': 1, 'b': 2, 'c': 3}

If the lists have different lengths, the zip() function will truncate the longer list to match the length of the shorter list. Here is an example.


# Two lists with different lengths
my_keys = ['a', 'b', 'c']
my_values = [1, 2, 3, 4]

my_dict = dict(zip(my_keys, my_values))
print(my_dict)  

# Output: 
# {'a': 1, 'b': 2, 'c': 3}

If there are two keys with the same name, the dict() constructor will only keep the last value associated with the key. This is because, in a dictionary, each key can only have one corresponding value.


# A list with two same elements
keys_list = ['a', 'b', 'c', 'a']
values_list = [1, 2, 3, 4]

my_dict = dict(zip(keys_list, values_list))
print(my_dict)  

# Output: 
# {'a': 4, 'b': 2, 'c': 3}

3. Dictionary Comprehension to Convert Two Lists to Dict

Another method to convert two lists into a dictionary is by using dictionary comprehension. A dictionary comprehension is a concise and more pythonic way to create a new dictionary from an iterable by specifying how the keys and values should be mapped to each other.

See the following example.


# Create a dictionary using a dictionary comprehension
my_dict = {keys_list[i]: values_list[i] for i in range(len(keys_list))}

# Print the resulting dictionary
print(my_dict)  

# Output: 
# {'a': 1, 'b': 2, 'c': 3}

Just like the zip() method, if the keys in the keys list are not unique, then the resulting dictionary will only contain the value of the last occurrence of the key.


# With duplicate elements in list
keys_list = ['a', 'b', 'a']
values_list = [1, 2, 3]

my_dict = {keys_list[i]: values_list[i] for i in range(len(keys_list))}
print(my_dict) 

# Output: 
# {'a': 3, 'b': 2}

4. Using enumerate()

You can use the enumerate() function to add a counter to an iterable object, such as a list, and return an enumerate object. This object contains pairs of the form (index, element) for each element in the iterable.

We can use this function in combination with a loop to create or convert a dictionary from two list. see the below python example.


# Using the enumerate() function
# These are two lists for keys and values
keys_list = ['a', 'b', 'c', 'd']
values_list = [1, 2, 3, 4]

# First we create an empty dict
my_dict = {}
for index, value in enumerate(values_list):
    my_dict[keys_list[index]] = value

print(my_dict)  

# Output: 
# {'a': 1, 'b': 2, 'c': 3, 'd': 4}

5. fromkeys() – Dictionary from Keys and Values List

Last but not least is using fromkeys() method. The fromkeys() method creates a new dictionary with keys from the specified iterable and sets all of their values to None (if no value is specified). Then we can use a for loop to iterate over the keys in the dictionary and set their values to the corresponding value from values_list.

This method is useful when we have a list of keys and want to assign the same value to each key.


# The formkeys Methodo
# First create a dictionary from Keys
my_dict = dict.fromkeys(keys_list)

# We then assign values to it
key_index = 0
for key in my_dict:
    my_dict[key] = values_list[key_index]
    key_index += 1

print(my_dict)

This method can also be used to create a dictionary with default values for all keys, by specifying a default value as the second argument to the fromkeys() method.


# Using the default parameter
keys_list = ['a', 'b', 'c', 'd']
default_value = 0
my_dict = dict.fromkeys(keys_list, default_value)

# Output:
# {'a': 0, 'b': 0, 'c': 0, 'd': 0}

Below are some of the good features of this method:

  • If the length of values_list is less than the length of keys_list, the remaining keys in the dictionary will have their values set to None.
  • If the length of values_list is greater than the length of keys_list, the extra values will be ignored.

6. Summary and Conclusion

In this article, we have discussed four different methods to convert two lists to a python dictionary or create a dictionary from python lists. I hope this article was helpful. If you have any questions, please leave them in the comment section.

Happy Coding!