A Python dictionary is a data structure that stores values in key-value pairs. It is one of the most versatile and widely used data structures in Python. Dictionaries are unordered (as of Python 3.6+, they maintain insertion order), mutable, and indexed by keys, which must be immutable types (like strings, numbers, or tuples). Values in a dictionary can be of any data type and can be duplicated, whereas keys can’t be repeated and must be immutable.
Creating a Python Dictionary
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
print(person)This defines a dictionary with three key-value pairs. Keys are strings, and values are strings and integers.
Accessing Dictionary Items
print(person["name"]) # Output: Alice
print(person.get("age")) # Output: 30Use square brackets to access values by key. get() is safer and won’t throw an error if the key doesn’t exist.
Adding and Updating Items
person["email"] = "alice@example.com"
person["age"] = 31
print(person)Assigning to a key adds it if it’s new, or updates the value if the key already exists.
Removing Items from a Python Dictionary
person.pop("city")
print(person)pop() removes a key and returns its value. You can also use it del person["name"] to delete a key-value pair.
Python Dictionary Methods
print(person.keys()) # dict_keys(['name', 'age', 'email'])
print(person.values()) # dict_values(['Alice', 31, 'alice@example.com'])
print(person.items()) # dict_items([('name', 'Alice'), ('age', 31), ('email', 'alice@example.com')])Use keys(), values(), and items() to retrieve dictionary contents.
Iterating Through a Python Dictionary
for key, value in person.items():
print(f"{key}: {value}")Loop through key-value pairs using items(). This is commonly used for logging or printing structured data.
Checking if a Key Exists
if "email" in person:
print("Email is present")Use the in keyword to check for the presence of a key in the dictionary.
Dictionary Comprehension
squares = {x: x*x for x in range(5)}
print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}Dictionary comprehensions offer a concise way to create dictionaries using loops.
Nested Python Dictionaries
students = {
"001": {"name": "Alice", "score": 85},
"002": {"name": "Bob", "score": 90}
}
print(students["001"]["name"]) # Output: AliceYou can store dictionaries inside dictionaries to represent structured data, like records or configurations.
Copying Dictionaries
copy_dict = person.copy()
print(copy_dict)copy() creates a shallow copy of the dictionary.
Clearing All Items
person.clear()
print(person) # Output: {}Use clear() to empty a dictionary without deleting the variable itself.
Merging Python Dictionaries
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = {**dict1, **dict2}
print(merged) # Output: {'a': 1, 'b': 3, 'c': 4}This merges two dictionaries. If there are duplicate keys, the right-hand dictionary’s values overwrite the left’s.
Conclusion
Python dictionaries are an essential data structure for representing and managing key-value mappings. They are fast, dynamic, and highly versatile, making them a perfect choice for lookups, configuration settings, counters, JSON-like data, and more.
By mastering dictionary operations—creation, access, update, iteration, and comprehension—you can greatly enhance the efficiency and clarity of your Python programs.
