(toc)
A dictionary in Python is an unordered collection of items, where each item is stored as a key-value pair. Dictionaries are mutable, meaning you can change them after they are created. They are widely used for storing and accessing data in a key-value format, making it easy to retrieve and manipulate data efficiently.
Key Features of Dictionaries
- Unordered: The order of items in a dictionary is not guaranteed (before Python 3.7). In Python 3.7+, dictionaries maintain insertion order.
- Mutable: You can modify dictionaries by adding, removing, or updating key-value pairs.
- Unique Keys: A dictionary cannot have duplicate keys. Each key must be unique.
- Key-Value Pairs: Each dictionary element consists of a key and an associated value.
- Keys Must Be Immutable: The keys in a dictionary must be of an immutable data type (e.g., strings, numbers, or tuples).
Creating a Dictionary
You can create a dictionary using curly braces {}
or the dict()
constructor.
Examples:
# Creating a dictionary with curly braces person = { "name": "Alice", "age": 30, "city": "New York" } # Creating a dictionary using the dict() constructor student = dict(name="John", age=21, major="Computer Science") print(person) # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'} print(student) # Output: {'name': 'John', 'age': 21, 'major': 'Computer Science'}
Accessing Dictionary Elements
You can access the value of a specific key by using the key inside square brackets []
or by using the get()
method.
Examples:
person = { "name": "Alice", "age": 30, "city": "New York" } # Accessing value using key print(person["name"]) # Output: Alice # Using get() method print(person.get("city")) # Output: New York # Using get() with default value if key does not exist print(person.get("country", "USA")) # Output: USA (default value since key "country" doesn't exist)
Modifying Dictionaries
You can add, update, or remove key-value pairs in a dictionary.
-
Adding or Updating
If the key exists, its value will be updated; if the key does not exist, a new key-value pair is added.person = { "name": "Alice", "age": 30, "city": "New York" } # Adding a new key-value pair person["email"] = "alice@example.com" # Updating an existing key-value pair person["age"] = 31 print(person) # Output: {'name': 'Alice', 'age': 31, 'city': 'New York', 'email': 'alice@example.com'}
-
Removing Elements
You can usedel
or thepop()
method to remove elements.del
removes a key-value pair by key.pop()
removes a key-value pair and returns the value.
person = { "name": "Alice", "age": 30, "city": "New York" } # Using del to remove a key-value pair del person["age"] # Using pop() to remove a key-value pair and get the value city = person.pop("city") print(city) # Output: New York print(person) # Output: {'name': 'Alice'}
-
Removing All Elements
To remove all items in a dictionary, use theclear()
method.person.clear() print(person) # Output: {}
Dictionary Methods
Python dictionaries have several built-in methods that help with data manipulation:
Method | Description |
---|---|
keys() |
Returns a view object that displays all the keys. |
values() |
Returns a view object that displays all the values. |
items() |
Returns a view object that displays key-value pairs. |
get(key) |
Returns the value associated with the given key. |
pop(key) |
Removes and returns the value of the specified key. |
popitem() |
Removes and returns a random key-value pair. |
update(dict) |
Updates the dictionary with key-value pairs from another dictionary. |
clear() |
Removes all items from the dictionary. |
Examples:
person = { "name": "Alice", "age": 30, "city": "New York" } # Using keys(), values(), and items() print(person.keys()) # Output: dict_keys(['name', 'age', 'city']) print(person.values()) # Output: dict_values(['Alice', 30, 'New York']) print(person.items()) # Output: dict_items([('name', 'Alice'), ('age', 30), ('city', 'New York')]) # Using popitem() random_item = person.popitem() print(random_item) # Output: ('city', 'New York') print(person) # Output: {'name': 'Alice', 'age': 30}
Nested Dictionaries
A dictionary can contain another dictionary as a value. This is useful when you want to store more complex data structures.
Example:
company = { "employee1": { "name": "Alice", "age": 30, "position": "Engineer" }, "employee2": { "name": "Bob", "age": 25, "position": "Designer" } } print(company["employee1"]["name"]) # Output: Alice
Dictionary Comprehension
You can create dictionaries using dictionary comprehensions, similar to list comprehensions.
Example:
# Creating a dictionary of squares using dictionary comprehension squares = {x: x**2 for x in range(1, 6)} print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Use Cases of Dictionaries
-
Storing Data with Unique Identifiers
Dictionaries are ideal for storing data that needs to be accessed by a unique key, such as storing user profiles, settings, or configurations. -
Fast Lookups
Dictionaries allow fast lookups of values by key, making them useful for situations where you need to quickly retrieve data based on a known identifier. -
Counting Frequencies
You can use dictionaries to count the frequency of items in a collection (e.g., counting words in a text).text = "apple banana apple cherry apple" word_count = {} for word in text.split(): if word in word_count: word_count[word] += 1 else: word_count[word] = 1 print(word_count) # Output: {'apple': 3, 'banana': 1, 'cherry': 1}