How to Create Dictionary from List in Python: Simple Guide
You can create a dictionary from a list in Python by using
dict() with a list of key-value pairs or by using a dictionary comprehension to assign keys and values. For example, use dict([(key, value), ...]) or {key: value for item in list} to build the dictionary.Syntax
There are two common ways to create a dictionary from a list:
- Using
dict()with a list of tuples: Each tuple contains a key and a value. - Using dictionary comprehension: You write a short expression to generate key-value pairs from the list.
python
dict([(key1, value1), (key2, value2), ...]) # or {key_expression: value_expression for item in list}
Example
This example shows how to create a dictionary from a list of numbers where keys are the numbers and values are their squares.
python
numbers = [1, 2, 3, 4] squares_dict = {num: num ** 2 for num in numbers} print(squares_dict)
Output
{1: 1, 2: 4, 3: 9, 4: 16}
Common Pitfalls
Common mistakes include:
- Trying to convert a list of single values directly to a dictionary without pairing keys and values.
- Using lists with duplicate keys, which will overwrite previous values.
- Not using tuples or pairs inside
dict(), which causes errors.
python
wrong_list = [1, 2, 3] # This will cause an error because items are not key-value pairs # my_dict = dict(wrong_list) # Raises TypeError # Correct way with pairs: pairs = [(1, 'a'), (2, 'b'), (3, 'c')] my_dict = dict(pairs) print(my_dict)
Output
{1: 'a', 2: 'b', 3: 'c'}
Quick Reference
Summary tips for creating dictionaries from lists:
- Use
dict()with a list of(key, value)tuples. - Use dictionary comprehension for flexible key-value creation.
- Ensure keys are unique to avoid overwriting.
- Remember dictionary keys must be immutable types like strings, numbers, or tuples.
Key Takeaways
Use dict() with a list of (key, value) pairs to create a dictionary from a list.
Dictionary comprehension offers a concise way to build dictionaries from lists.
Keys must be unique and immutable to avoid errors or overwriting values.
Avoid passing a list of single values directly to dict(), it requires pairs.
Dictionary comprehension allows custom logic for keys and values from list items.