Python > Core Python Basics > Data Structures > Dictionaries
Creating and Accessing Dictionaries in Python
This snippet demonstrates the fundamental operations of creating, accessing, and modifying dictionaries in Python. Dictionaries are a powerful data structure that store data in key-value pairs, allowing for efficient data retrieval and manipulation.
Creating a Dictionary
This code creates a dictionary named `my_dict`. It uses curly braces `{}` to define the dictionary. Each element within the dictionary consists of a key-value pair, separated by a colon `:`. Keys are typically strings or numbers (must be immutable), and values can be any Python data type. In this example, the keys are 'name', 'age', and 'city', and their corresponding values are 'Alice', 30, and 'New York'. The `print()` function displays the contents of the dictionary.
my_dict = {
'name': 'Alice',
'age': 30,
'city': 'New York'
}
print(my_dict)
Accessing Values
This demonstrates how to access values in a dictionary using their keys. You use square brackets `[]` with the key inside to retrieve the associated value. For example, `my_dict['name']` retrieves the value associated with the key 'name', which is 'Alice'. The `print()` statements display the retrieved values. It is important to verify the key exists before trying to access it as this operation may raise an error.
name = my_dict['name']
age = my_dict['age']
print(f'Name: {name}')
print(f'Age: {age}')
Modifying Values
Dictionaries are mutable, meaning you can change the values associated with existing keys. This code demonstrates how to modify the 'age' and 'city' values in the `my_dict` dictionary. You simply assign a new value to the key using the assignment operator `=`. The `print()` function displays the updated dictionary.
my_dict['age'] = 31
my_dict['city'] = 'Los Angeles'
print(my_dict)
Adding New Key-Value Pairs
You can also add new key-value pairs to a dictionary. This is done by simply assigning a value to a new key that doesn't already exist in the dictionary. In this example, the key 'occupation' is added to `my_dict` with the value 'Engineer'. The `print()` function shows the dictionary with the newly added key-value pair.
my_dict['occupation'] = 'Engineer'
print(my_dict)
Checking for Key Existence
The `in` operator is used to check if a key exists in a dictionary. `'name' in my_dict` returns `True` if the key 'name' exists in `my_dict`, and `False` otherwise. The `not in` operator does the opposite. This is useful to avoid `KeyError` exceptions when accessing keys that might not exist.
if 'name' in my_dict:
print('Name exists in the dictionary')
if 'country' not in my_dict:
print('Country does not exist in the dictionary')
concepts behind the snippet
This snippet covers the core concepts of dictionary creation, access, modification, and key existence checks. Dictionaries provide a way to map keys to values, enabling fast lookups. Keys must be immutable, ensuring that the lookup remains consistent. Understanding these concepts is crucial for effectively using dictionaries in Python.
Real-Life Use Case Section
Dictionaries are used extensively in web development. For example, when you receive data from an API (like user information), it's often structured as a JSON object, which Python represents as a dictionary. You can easily access specific fields like `user['name']` or `user['email']`. In data analysis, dictionaries can store aggregated results. Imagine counting the occurrences of words in a document: the word can be the key and the count can be the value.
data = {
"employee_id": "E123",
"name": "Bob Johnson",
"department": "Engineering",
"salary": 75000
}
print(f"Employee Name: {data['name']}")
print(f"Employee Salary: {data['salary']}")
When to use them
Use dictionaries when you need to store data as key-value pairs. Dictionaries allow you to store related data in a structured way. They're appropriate for representing objects (like database records) and configurations. Also when you need to access element with a key and not an index.
Memory footprint
Dictionaries are hash tables, which means they generally offer O(1) (constant time) average complexity for lookups, insertions, and deletions. However, there's a memory overhead associated with storing the hash table. In certain situations where memory is extremely constrained, or you're only using integer keys, consider alternatives like lists (indexed by integers). The larger the dictionary gets, the more memory it will consume. However, modern Python implementations are very efficient at dictionary storage.
pros
cons
FAQ
-
What happens if I try to access a key that doesn't exist?
If you try to access a key that doesn't exist in a dictionary using square bracket notation (e.g., `my_dict['nonexistent_key']`), Python will raise a `KeyError` exception. To avoid this, you can use the `get()` method or check for the key's existence using the `in` operator. -
Are dictionary keys ordered?
In Python versions prior to 3.7, dictionaries were unordered. However, starting with Python 3.7, dictionaries preserve insertion order. This means the keys will be iterated over in the order they were inserted into the dictionary. -
Can I use a list as a dictionary key?
No, dictionary keys must be immutable. Lists are mutable, so you cannot use them as keys. You can use tuples, strings, numbers, or other immutable objects as keys.