Creating Dictionaries
Dictionary Initialization Methods
1. Literal Notation
The most straightforward way to create a dictionary is using curly braces:
## Simple dictionary creation
person = {"name": "John", "age": 30, "city": "New York"}
## Empty dictionary
empty_dict = {}
2. dict() Constructor
Python provides the dict() constructor for creating dictionaries:
## Creating dictionary using dict() constructor
student = dict(name="Alice", age=22, major="Computer Science")
## From list of tuples
contact_info = dict([
("email", "user@example.com"),
("phone", "123-456-7890")
])
Advanced Dictionary Creation Techniques
3. Dictionary Comprehension
Create dictionaries dynamically using comprehension:
## Generate a dictionary of squares
squares = {x: x**2 for x in range(6)}
## Result: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
## Conditional dictionary comprehension
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
4. Nested Dictionaries
## Nested dictionary example
school = {
"class_A": {
"teacher": "Mr. Smith",
"students": ["Alice", "Bob", "Charlie"]
},
"class_B": {
"teacher": "Ms. Johnson",
"students": ["David", "Eve", "Frank"]
}
}
Dictionary Creation Strategies
graph TD
A[Dictionary Creation Methods] --> B[Literal Notation]
A --> C[dict() Constructor]
A --> D[Comprehension]
A --> E[Nested Dictionaries]
Conversion Methods
From Other Data Structures
## From lists
keys = ['a', 'b', 'c']
values = [1, 2, 3]
converted_dict = dict(zip(keys, values))
## From list of tuples
tuple_list = [('x', 10), ('y', 20), ('z', 30)]
dict_from_tuples = dict(tuple_list)
Practical Considerations
| Method |
Pros |
Cons |
| Literal Notation |
Simple, readable |
Limited for dynamic creation |
| dict() Constructor |
Flexible |
Slightly more verbose |
| Comprehension |
Powerful, concise |
Can be complex for beginners |
Best Practices
- Use the most readable method for your specific use case
- Prefer comprehensions for simple, predictable transformations
- Consider performance for large dictionaries
LabEx Tip
At LabEx, we recommend practicing these dictionary creation techniques to become proficient in Python data manipulation.