How to Create Dictionary from Two Lists in Python
You can create a dictionary from two lists in Python by using the
zip() function to pair elements and then converting it to a dictionary with dict(). Alternatively, use dictionary comprehension with zip() to build the dictionary in one step.Syntax
To create a dictionary from two lists, use the zip() function to pair elements from both lists, then convert the pairs into a dictionary with dict().
Syntax:
dict(zip(list1, list2)): Creates a dictionary where elements oflist1are keys and elements oflist2are values.{k: v for k, v in zip(list1, list2)}: Dictionary comprehension alternative to build the dictionary.
python
dictionary = dict(zip(list1, list2))
Example
This example shows how to create a dictionary from two lists: one with keys and one with values. It uses zip() and dict() to combine them.
python
keys = ['apple', 'banana', 'cherry'] values = [1, 2, 3] fruit_dict = dict(zip(keys, values)) print(fruit_dict)
Output
{'apple': 1, 'banana': 2, 'cherry': 3}
Common Pitfalls
Common mistakes include:
- Lists of different lengths:
zip()stops at the shortest list, so some items may be lost. - Using mutable types as keys, which is not allowed in dictionaries.
- Confusing keys and values order.
Always ensure keys list contains unique and immutable elements.
python
keys = ['a', 'b', 'c', 'd'] values = [1, 2] # Wrong: This will ignore extra keys silently result = dict(zip(keys, values)) print(result) # Output: {'a': 1, 'b': 2} # Right: Make sure lists are same length or handle missing values values = [1, 2, 3, 4] result = dict(zip(keys, values)) print(result) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Output
{'a': 1, 'b': 2}
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Quick Reference
Summary tips for creating dictionaries from two lists:
- Use
dict(zip(keys, values))for a quick dictionary. - Ensure keys are unique and immutable (like strings or numbers).
- Check lists have the same length to avoid missing data.
- Dictionary comprehension with
{k: v for k, v in zip(keys, values)}is an alternative.
Key Takeaways
Use zip() to pair elements from two lists and dict() to create the dictionary.
Ensure the keys list contains unique and immutable items.
If lists differ in length, zip() stops at the shortest list, possibly losing data.
Dictionary comprehension with zip() offers a flexible alternative.
Always verify keys and values order to avoid confusion.