Building Dictionaries in Python
Creating a dictionary is often the first step in organizing your data. Python provides several flexible and expressive ways to build dictionaries, each suited for different situations. Choosing the right method can make your code more readable and efficient.
Let’s explore the most common patterns for dictionary creation.
1. The Dictionary Literal: {}
The most common and straightforward way to create a dictionary is by using curly braces {}
. You define a comma-separated series of key: value
pairs inside the braces.
Pyground
Create a dictionary representing a student's profile using the literal syntax.
Expected Output:
{'name': 'Aarav Sharma', 'grade': 12, 'is_enrolled': True, 'subjects': ['Math', 'Computer Science', 'Physics']}
Output:
Key Requirements: Dictionary keys must be of an immutable and hashable type. This includes strings, numbers, and tuples. You cannot use mutable types like lists or other dictionaries as keys. Values, however, can be any Python object.
2. The dict()
Constructor
The built-in dict()
constructor offers another flexible way to create dictionaries. It can be used in several ways.
From Keyword Arguments
This method is useful when your keys are simple strings that are valid Python identifiers.
Pyground
Create a configuration dictionary using the `dict()` constructor with keyword arguments.
Expected Output:
{'debug': True, 'retries': 3, 'user': 'admin'}
Output:
3. Dictionary Comprehensions
For creating dictionaries from existing iterables in a concise way, dictionary comprehensions are incredibly powerful. The syntax is {key_expression: value_expression for item in iterable}
.
Pyground
Create a dictionary that maps numbers from 1 to 5 to their squares.
Expected Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Output:
You can also add a conditional to the comprehension.
Pyground
From a list of numbers, create a dictionary mapping only the even numbers to their cubes.
Expected Output:
{2: 8, 4: 64, 6: 216}
Output:
4. Using zip()
The zip()
function is perfect for creating a dictionary when you have keys and values in separate lists. It pairs up elements from each list, and dict()
can turn these pairs into a dictionary.
Pyground
Create a profile dictionary from a list of keys and a list of values.
Expected Output:
{'name': 'Mira', 'city': 'Jaipur', 'age': 19}
Output:
zip()
stops as soon as one of the lists runs out of items. If the lists have different lengths, the extra items in the longer list will be ignored.
5. Using dict.fromkeys()
This class method is used to create a new dictionary with keys from a given sequence, where all keys have the same specified value.
Pyground
Initialize a dictionary to track the status of several features, all starting as `False`.
Expected Output:
{'dark_mode': False, 'notifications': False, 'auto_save': False}