How to create a dictionary from two lists in Python

Discover multiple ways to create a dictionary from two lists in Python. Get tips, see real-world examples, and learn to debug common errors.

How to create a dictionary from two lists in Python
Published on: 
Mon
Apr 6, 2026
Updated on: 
Wed
Apr 8, 2026
The Replit Team

A common Python task is to combine two lists into a dictionary. This is essential when you need to organize related data into key-value pairs. Python offers several efficient methods to do this.

In this article, you'll learn different techniques, from the zip() function to dictionary comprehensions. We'll cover practical tips, real-world applications, and advice on how to debug common errors.

Using zip() and dict() to create a dictionary

keys = ['name', 'age', 'job']
values = ['John', 30, 'Developer']
my_dict = dict(zip(keys, values))
print(my_dict)--OUTPUT--{'name': 'John', 'age': 30, 'job': 'Developer'}

This approach is elegant because it combines two built-in Python functions. The zip() function acts as a zipper, merging the keys and values lists. It pairs each key with its corresponding value based on their index, creating a sequence of tuples like ('name', 'John').

The dict() constructor then takes this sequence of key-value pairs and assembles the final dictionary. This method is highly Pythonic—it's concise, readable, and efficient for creating a dictionary from two lists of the same length.

Basic dictionary creation methods

While the zip() function is highly efficient, using for loops or dictionary comprehensions can give you more flexibility when building your dictionary.

Creating a dictionary with a for loop

keys = ['a', 'b', 'c']
values = [1, 2, 3]
result = {}
for i in range(len(keys)):
result[keys[i]] = values[i]
print(result)--OUTPUT--{'a': 1, 'b': 2, 'c': 3}

Using a for loop offers a more manual but highly flexible approach. You begin by creating an empty dictionary. The loop then iterates over a sequence of indices generated by range(len(keys)).

  • In each iteration, the loop uses an index to retrieve a key from the keys list and a corresponding value from the values list.
  • It then assigns this key-value pair directly to your new dictionary.

This method is useful when you need to add conditional logic or perform transformations while building the dictionary.

Using dictionary comprehension

keys = ['apple', 'banana', 'orange']
values = [0.5, 0.3, 0.7]
fruit_prices = {keys[i]: values[i] for i in range(len(keys))}
print(fruit_prices)--OUTPUT--{'apple': 0.5, 'banana': 0.3, 'orange': 0.7}

Dictionary comprehension offers a more compact and elegant syntax for creating dictionaries. It essentially condenses a for loop into a single, readable line inside curly braces {}.

  • The expression keys[i]: values[i] defines how each key-value pair is formed.
  • The loop for i in range(len(keys)) iterates over the indices to pair elements correctly.

This method is very Pythonic and is often preferred for its clarity and conciseness when your logic is straightforward.

Combining zip() with dictionary comprehension

colors = ['red', 'green', 'blue']
hex_codes = ['#FF0000', '#00FF00', '#0000FF']
color_dict = {k: v for k, v in zip(colors, hex_codes)}
print(color_dict)--OUTPUT--{'red': '#FF0000', 'green': '#00FF00', 'blue': '#0000FF'}

Combining zip() with dictionary comprehension is a powerful and clean way to build your dictionary. This approach leverages the best of both worlds. The zip() function first pairs corresponding elements from your lists into tuples.

  • The dictionary comprehension then unpacks each tuple into a key k and a value v.
  • This is often more readable than iterating over indices with range().

You get a concise, single line of code that clearly expresses your intent—turning two lists into a dictionary.

Advanced dictionary techniques

While the methods we've covered are powerful, real-world data isn't always so neat, requiring techniques for handling mismatched lists or more complex dictionary structures.

Handling lists of different lengths

keys = ['a', 'b', 'c', 'd']
values = [1, 2, 3]
from itertools import zip_longest
result = dict(zip_longest(keys, values, fillvalue='N/A'))
print(result)--OUTPUT--{'a': 1, 'b': 2, 'c': 3, 'd': 'N/A'}

When your lists have different lengths, the standard zip() function truncates the output, stopping as soon as the shorter list is exhausted. This can lead to lost data. The solution is zip_longest() from Python's itertools module.

  • This function continues pairing items until the end of the longest list is reached.
  • You can specify a fillvalue to assign a default to any keys that don't have a corresponding value, ensuring every key from the longer list makes it into your dictionary.

Using defaultdict for specialized dictionaries

from collections import defaultdict
keys = ['apple', 'banana', 'apple', 'orange']
values = [2, 3, 5, 1]
fruit_count = defaultdict(int)
for k, v in zip(keys, values):
fruit_count[k] += v
print(dict(fruit_count))--OUTPUT--{'apple': 7, 'banana': 3, 'orange': 1}

A defaultdict is your go-to when you have duplicate keys and need to aggregate data, such as summing values. It's a specialized dictionary from Python's collections module that provides a default value for keys that don't exist yet.

  • By initializing with defaultdict(int), any new key you access is automatically given a starting value of 0.
  • This lets you use operators like += without causing a KeyError, making it simple to accumulate values for keys like 'apple' as you loop through your lists.

Creating dictionaries with multiple values per key

from collections import defaultdict
keys = ['fruit', 'vegetable', 'fruit', 'protein']
values = ['apple', 'carrot', 'banana', 'chicken']
category_dict = defaultdict(list)
for k, v in zip(keys, values):
category_dict[k].append(v)
print(dict(category_dict))--OUTPUT--{'fruit': ['apple', 'banana'], 'vegetable': ['carrot'], 'protein': ['chicken']}

Sometimes you need to group multiple items under a single key. A defaultdict is perfect for this when initialized with list. This setup allows you to collect all values associated with duplicate keys into a list, which is ideal for categorizing data.

  • By using defaultdict(list), any new key is automatically given an empty list as its value.
  • This lets you call .append() on the key's value without checking if the key exists first, neatly grouping items like 'apple' and 'banana' under the 'fruit' key.

Move faster with Replit

Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. This environment lets you move beyond practicing individual techniques and start building complete applications with the help of Agent 4.

Instead of piecing together functions, you can describe the app you want to build, and Agent will take it from idea to working product. For example, you could build:

  • A configuration manager that combines a list of setting keys and a list of values into a single settings dictionary.
  • A data reconciliation tool that merges two lists of different lengths—like products and their inventory counts—using a default value for items that are out of stock.
  • A content organizer that groups a list of articles under their corresponding categories, even when categories are repeated, by using a structure similar to defaultdict(list).

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

Even with the right tools, you can run into a few common pitfalls when combining lists into a dictionary.

  • When handling mismatched list lengths, be aware that the standard zip() function can cause silent data loss. It stops as soon as the shorter list runs out of items, so any extra elements in the longer list are simply ignored.
  • This won't crash your code, which makes the bug difficult to spot until you notice your dictionary is incomplete.
  • A TypeError is another common issue, especially when using defaultdict. This error occurs if you mismatch the default factory with the operation you're performing.
  • For example, initializing with defaultdict(list) but then trying to add a number with += will fail because you can't add an integer to a list. Always ensure the factory—like int for counting or list for appending—matches your goal.
  • A KeyError is a frequent runtime error that stops your program when it tries to access a dictionary key that doesn't exist. This often happens when iterating or working with dynamic data where you can't be sure a key will be present.
  • To prevent this, you can use the .get() method, which safely returns None or a specified default value if the key is missing. Another safe approach is to check if a key exists first using the in keyword before you try to access it.

Handling mismatched list lengths with zip()

When your key and value lists aren't the same size, the zip() function can cause silent data loss. It simply ignores extra items from the longer list, creating an incomplete dictionary. The code below demonstrates this common pitfall.

keys = ['name', 'age', 'job', 'city']
values = ['Alice', 25, 'Engineer']
user_info = dict(zip(keys, values))
print(user_info) # Missing 'city' key

The zip() function pairs elements until the shorter values list runs out. This leaves the 'city' key without a value, so it's excluded from the final dictionary. The code below demonstrates how to handle this correctly.

from itertools import zip_longest
keys = ['name', 'age', 'job', 'city']
values = ['Alice', 25, 'Engineer']
user_info = dict(zip_longest(keys, values, fillvalue='Unknown'))
print(user_info)

The solution is to use zip_longest() from the itertools module. Unlike the standard zip(), this function doesn't stop early. It continues until the longest list is exhausted, and the fillvalue parameter lets you specify a default for any keys that lack a value. This prevents data loss and ensures your dictionary includes all keys—crucial when working with datasets of unpredictable lengths, like API responses or user inputs.

Avoiding type errors with defaultdict

A defaultdict can raise a TypeError if you forget to provide a default factory, like int or list. Without one, it can't create a starting value for new keys, causing errors with operators like +=. The following code demonstrates this common mistake.

from collections import defaultdict
word_count = defaultdict()
text = "hello world hello python"
for word in text.split():
word_count[word] += 1
print(word_count)

The defaultdict() is missing its factory argument. When the loop tries to increment a word's count using +=, it has no starting number to add to, which triggers a TypeError. The corrected approach is shown below.

from collections import defaultdict
word_count = defaultdict(int)
text = "hello world hello python"
for word in text.split():
word_count[word] += 1
print(dict(word_count))

By initializing with defaultdict(int), you provide a "factory" that automatically gives any new key a starting value of 0. This prevents a TypeError because the += operator now has a number to add to, even on the first encounter of a key.

  • This is essential when building frequency counters or aggregating data where you can't predict which keys will appear.

Preventing KeyError when accessing dictionary values

Accessing a dictionary key that doesn't exist will trigger a KeyError, a runtime error that immediately stops your program. This is a frequent issue when dealing with incomplete datasets or unpredictable inputs where certain keys might be missing.

The following code shows what happens when you try to retrieve the 'occupation' key from a dictionary that doesn't contain it.

user_data = {'name': 'John', 'age': 30}
occupation = user_data['occupation']
print(f"Name: {user_data['name']}, Occupation: {occupation}")

The program crashes because the code attempts to access the 'occupation' key directly, but it doesn't exist in the dictionary. This direct access with bracket notation triggers a KeyError. The code below shows how to avoid this.

user_data = {'name': 'John', 'age': 30}
occupation = user_data.get('occupation', 'Unknown')
print(f"Name: {user_data['name']}, Occupation: {occupation}")

The solution is to use the dictionary’s .get() method, which safely handles missing keys. Instead of causing a KeyError, it returns a default value if the key isn't found.

  • The expression user_data.get('occupation', 'Unknown') looks for the 'occupation' key. Since it's missing, the method returns the default value you provided, 'Unknown'. This is essential when you're working with unpredictable data, like API responses or user input, where keys may not always be present.

Real-world applications

Beyond theory and error handling, these methods are essential for practical tasks like processing CSV files or analyzing sales data.

Processing CSV data with zip()

A common real-world task is processing CSV data, where zip() excels at pairing column headers with the data in each row to create structured dictionaries.

# Sample CSV data (simulating read from a file)
csv_data = """id,name,age,occupation
1,John Smith,28,Engineer
2,Jane Doe,34,Data Scientist
3,Mike Johnson,45,Manager"""

# Process the CSV data
lines = csv_data.strip().split('\n')
headers = lines[0].split(',')
people = []

for line in lines[1:]:
values = line.split(',')
people.append(dict(zip(headers, values)))

print(people[1]) # Print the second person's data

This code efficiently transforms raw CSV text into a list of structured dictionaries. It first isolates the column headers from the first line of data. Then, it iterates through each subsequent data row, turning each one into its own dictionary.

  • Inside the loop, zip() pairs each header with its corresponding value from the current row.
  • The dict() constructor then converts these key-value pairs into a dictionary.
  • Finally, each new dictionary is appended to a list, making the data easy to access and manipulate.

Analyzing sales data with defaultdict

You can use a defaultdict to quickly organize sales data, grouping products and their prices by category.

from collections import defaultdict

# Sales data: (product, category, price)
sales = [
('Laptop', 'Electronics', 1200),
('T-shirt', 'Clothing', 25),
('Headphones', 'Electronics', 150),
('Jeans', 'Clothing', 50)
]

# Group by category using defaultdict
categories = defaultdict(list)
for product, category, price in sales:
categories[category].append((product, price))

print(dict(categories))

This code efficiently groups sales data by category. The defaultdict(list) is the key—it simplifies the process of sorting items without needing extra conditional checks to see if a category already exists.

  • As the code loops through the sales data, it unpacks each record into product, category, and price.
  • It then appends a (product, price) tuple to the list associated with the correct category key.

This approach automatically creates a new list for any new category it encounters, keeping your logic clean and focused on the task of grouping data.

Get started with Replit

Now, turn these techniques into a real tool. Describe what you want to build to Replit Agent, like “Create a CSV to JSON converter” or “Build a script that maps user IDs to usernames.”

Replit Agent will write the code, test for errors, and help you deploy your app. Start building with Replit.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.