Python Dictionary
Master Python dictionaries for AI and ML! Learn key-value pairs, mutability, and efficient data management in this comprehensive guide for developers.
3.8 Python Dictionaries: A Comprehensive Guide
Python dictionaries are a powerful and versatile built-in data structure used to store data as key-value pairs. They are ideal for situations where data is best represented through associations, such as:
Names and phone numbers
Product IDs and descriptions
Employee IDs and their records
Key Features of Dictionaries
Mutable: Dictionaries can be modified after creation (adding, updating, or removing items).
Ordered (Python 3.7+): Items are stored in the order they were inserted. In versions prior to Python 3.7, dictionaries were unordered.
Indexed using keys: Each value is associated with a unique key, which is used for accessing the value.
Unique keys: Keys within a single dictionary must be unique. If a duplicate key is added, the latest value associated with that key will overwrite the previous one.
Mapping type: Dictionaries establish a mapping between keys and their corresponding values.
Dictionary Syntax
A dictionary is defined using curly braces {}
with key-value pairs separated by colons :
. Each key-value pair is separated by a comma ,
.
dictionary_name = {key1: value1, key2: value2, ...}
Example:
state_capitals = {
"Andhra Pradesh": "Amaravati",
"Punjab": "Chandigarh",
"West Bengal": "Kolkata"
}
Creating Dictionaries
There are several ways to create dictionaries in Python:
1. Using Curly Braces {}
This is the most common and straightforward method.
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
2. Using the dict()
Constructor
The dict()
constructor can be used with keyword arguments or an iterable of key-value pairs.
Using keyword arguments:
employee = dict(name="Ravi", age=30, department="HR")
print(employee)
## Output: {'name': 'Ravi', 'age': 30, 'department': 'HR'}
Using an iterable of key-value pairs (e.g., a list of tuples):
student = dict([("name", "Anita"), ("score", 89), ("subject", "Math")])
print(student)
## Output: {'name': 'Anita', 'score': 89, 'subject': 'Math'}
3. Using dict.fromkeys()
This method creates a new dictionary with keys from a sequence and a common value (which defaults to None
).
keys = ["a", "b", "c"]
default_value = 0
new_dict = dict.fromkeys(keys, default_value)
print(new_dict)
## Output: {'a': 0, 'b': 0, 'c': 0}
Dictionary Key Rules
Immutable Types: Dictionary keys must be of an immutable data type. This includes:
Strings (
str
)Numbers (
int
,float
,complex
)Tuples (
tuple
)
No Mutable Keys: Mutable types like lists (
list
) or dictionaries (dict
) cannot be used as keys because their contents can change, which would break the integrity of the key-value mapping.
Example of valid keys:
valid_dict = {
"name": "Bob",
101: "Employee ID",
(1, 2): "Coordinates"
}
Example of invalid key (will raise TypeError
):
## This will raise a TypeError because a list is mutable
## invalid_dict = {["apple", "banana"]: "fruits"}
Duplicate Keys: If you attempt to assign a value to a key that already exists in the dictionary, the new value will overwrite the old one.
Example:
data = {"x": 10, "y": 20, "x": 30}
print(data)
## Output: {'x': 30, 'y': 20}
Accessing Dictionary Values
You can access the values associated with keys in two primary ways:
1. Using Square Brackets []
This method directly accesses the value using its key. If the key does not exist, it will raise a KeyError
.
student = {"name": "Anita", "score": 89}
print(student["name"])
## Output: Anita
## print(student["grade"]) # This would raise a KeyError
2. Using the get()
Method
The get()
method is a safer way to access values as it returns None
(or a specified default value) if the key is not found, instead of raising an error.
student = {"name": "Anita", "score": 89}
## Get the value for an existing key
print(student.get("score"))
## Output: 89
## Get the value for a non-existent key, with a default value
print(student.get("grade", "NA"))
## Output: NA
## Get the value for a non-existent key without a default (returns None)
print(student.get("age"))
## Output: None
Modifying a Dictionary
Dictionaries are mutable, meaning you can change their contents:
Update an Existing Value
Assign a new value to an existing key.
student = {"name": "Anita", "score": 89}
student["score"] = 95
print(student)
## Output: {'name': 'Anita', 'score': 95}
Add a New Key-Value Pair
Assign a value to a key that does not exist yet.
student = {"name": "Anita", "score": 95}
student["passed"] = True
print(student)
## Output: {'name': 'Anita', 'score': 95, 'passed': True}
Removing Elements from a Dictionary
You can remove items from a dictionary using several methods:
1. Using the del
Keyword
The del
keyword removes an item by its key. It raises a KeyError
if the key doesn't exist.
student = {"name": "Anita", "score": 95, "passed": True}
del student["score"]
print(student)
## Output: {'name': 'Anita', 'passed': True}
2. Using pop()
The pop(key)
method removes the item with the specified key and returns its value. It also raises a KeyError
if the key is not found, unless a default value is provided.
student = {"name": "Anita", "passed": True, "subject": "Math"}
removed_value = student.pop("passed")
print(removed_value) # Output: True
print(student) # Output: {'name': 'Anita', 'subject': 'Math'}
## Get value for a non-existent key with a default
default_removed = student.pop("grade", "Not found")
print(default_removed) # Output: Not found
3. Using popitem()
The popitem()
method removes and returns the last inserted key-value pair as a tuple. In Python versions prior to 3.7, it removed and returned an arbitrary key-value pair. It raises a KeyError
if the dictionary is empty.
student = {"name": "Anita", "subject": "Math", "grade": "A"}
last_item = student.popitem()
print(last_item) # Output: ('grade', 'A')
print(student) # Output: {'name': 'Anita', 'subject': 'Math'}
4. Using clear()
The clear()
method removes all items from the dictionary, making it empty.
student = {"name": "Anita", "subject": "Math"}
student.clear()
print(student)
## Output: {}
Iterating Through a Dictionary
You can iterate through a dictionary in various ways:
Iterating Through Keys (Default)
By default, iterating through a dictionary yields its keys.
employee = {"id": 101, "name": "Ravi", "role": "Manager"}
print("Iterating through keys:")
for key in employee:
print(key)
## Output:
## id
## name
## role
Iterating Through Values
Use the .values()
method to iterate only through the values.
employee = {"id": 101, "name": "Ravi", "role": "Manager"}
print("\nIterating through values:")
for value in employee.values():
print(value)
## Output:
## 101
## Ravi
## Manager
Iterating Through Key-Value Pairs
Use the .items()
method to iterate through both keys and values simultaneously as tuples.
employee = {"id": 101, "name": "Ravi", "role": "Manager"}
print("\nIterating through key-value pairs:")
for key, value in employee.items():
print(f"{key} => {value}")
## Output:
## id => 101
## name => Ravi
## role => Manager
Dictionary Operators in Python
Python offers operators for dictionary manipulation, especially for combining dictionaries.
Accessing Items
The square bracket []
operator is used to access values.
d1 = {"a": 1, "b": 2}
print(d1["b"]) # Output: 2
Union (|
) Operator (Python 3.9+)
The union operator combines two dictionaries. If keys overlap, the value from the right-hand dictionary is used.
d1 = {"a": 1, "b": 2}
d2 = {"c": 3, "d": 4}
combined = d1 | d2
print(combined) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
d3 = {"b": 20, "e": 5}
combined_overlap = d1 | d3
print(combined_overlap) # Output: {'a': 1, 'b': 20, 'e': 5}
Update (|=
) Operator (Python 3.9+)
The update operator updates a dictionary with items from another dictionary. It's similar to the update()
method but uses operator syntax.
d1 = {"a": 1, "b": 2}
d2 = {"c": 3, "d": 4}
d1 |= d2
print(d1) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
d1 = {"a": 1, "b": 2}
d3 = {"b": 20, "e": 5}
d1 |= d3
print(d1) # Output: {'a': 1, 'b': 20, 'e': 5}
Common Dictionary Methods
Here's a summary of frequently used dictionary methods:
| Method | Description | | :------------------------ | :------------------------------------------------------------------------------- | | clear()
| Removes all items from the dictionary. | | copy()
| Returns a shallow copy of the dictionary. | | fromkeys(seq, value)
| Creates a new dictionary with keys from a sequence and a common value. | | get(key[, default])
| Returns the value for the specified key. If key is not found, returns default
(or None
if default
is not specified). | | items()
| Returns a view object displaying a list of a dictionary's key-value tuple pairs. | | keys()
| Returns a view object displaying a list of all the keys in the dictionary. | | values()
| Returns a view object displaying a list of all the values in the dictionary. | | pop(key[, default])
| Removes the specified key and returns its value. Raises KeyError
if key is not found and no default is provided. | | popitem()
| Removes and returns the last inserted key-value pair as a tuple. Raises KeyError
if the dictionary is empty. | | setdefault(key[, default])
| Returns the value for the specified key. If the key is not found, it inserts the key with the specified default
value (defaults to None
) and returns the default
value. | | update(other_dict)
| Updates the dictionary with key-value pairs from another dictionary or an iterable. |
Example using setdefault()
:
my_dict = {"name": "Alice"}
## Key "name" exists, returns its value
print(my_dict.setdefault("name", "Bob")) # Output: Alice
## Key "age" does not exist, inserts it with default value and returns it
print(my_dict.setdefault("age", 25)) # Output: 25
print(my_dict) # Output: {'name': 'Alice', 'age': 25}
Built-in Functions for Dictionaries
Several built-in functions work directly with dictionaries:
| Function | Description | | :----------- | :---------------------------------------------------- | | len(dict)
| Returns the number of key-value pairs in the dictionary. | | type(dict)
| Returns the type of the object, which will be <class 'dict'>
. | | str(dict)
| Returns a string representation of the dictionary. |
Example:
info = {"brand": "Toyota", "year": 2020}
print(len(info)) # Output: 2
print(type(info)) # Output: <class 'dict'>
print(str(info)) # Output: {'brand': 'Toyota', 'year': 2020}
Interview Questions on Python Dictionaries
What is a Python dictionary and how does it differ from a list?
How do you create a dictionary in Python?
What types can be used as dictionary keys? Why can’t lists be keys?
How do you access values in a dictionary? Explain the difference between using
[]
and.get()
.How can you add or update items in a dictionary?
What methods are used to remove items from a dictionary? How do
pop()
andpopitem()
differ?How can you iterate through keys, values, and key-value pairs in a dictionary?
How do dictionary union (
|
) and update (|=
) operators work in Python 3.9+?What does the
setdefault()
method do in a dictionary?How can you create a new dictionary from a sequence of keys with a common value?
SEO Keywords: Python dictionary tutorial, Python dictionary methods, How to create a dictionary in Python, Python dictionary key rules, Accessing dictionary values Python, Modify Python dictionary, Python dictionary iteration, Python dictionary operators, Python dict update merge, Python dictionary pop popitem setdefault.