🗂️ Python Dictionary
A dictionary in Python is an ordered collection (from Python 3.7 onwards) of items stored as key/value pairs. Each key is a unique identifier associated with a value.
For example, if we want to store countries and their capitals, we can create a dictionary where the country names are keys and capitals are values.
Creating a Dictionary
capital_city = {"Nepal": "Kathmandu", "Italy": "Rome", "England": "London"}
print(capital_city)
Here:
Keys: "Nepal", "Italy", "England"
Values: "Kathmandu", "Rome", "London"
Keys and values can be of different types.
Example 1: Dictionary with Integer Keys
numbers = {1: "One", 2: "Two", 3: "Three"}
print(numbers)
Adding Elements
capital_city["Japan"] = "Tokyo"
print(capital_city)
Changing Values
student_id = {112: "Kyle", 113: "Maria"}
student_id[112] = "Stan"
print(student_id)
Accessing Elements
print(capital_city["Italy"]) # Output: Rome
# Accessing a non-existing key will raise an error
# print(capital_city["Germany"]) # KeyError
Removing Elements
student_id = {111: "Alice", 112: "Bob"}
del student_id[111] # removes the key 111
print(student_id)
# del student_id # deletes the entire dictionary
Dictionary Methods
Dictionaries come with many useful methods such as keys(), values(), items(), get(), and update().
Membership Test
squares = {1: 1, 2: 4, 3: 9}
print(2 in squares) # True
print(5 in squares) # False
Iterating Through a Dictionary
squares = {1: 1, 2: 4, 3: 9}
for key in squares:
print(f"Key: {key}, Value: {squares[key]}")
📌 Try Yourself:
[Add your "Try Yourself" interactive Python editor here]
🔗 More Resources
💡 Note: You can create dictionaries with mixed key and value types. For example:
random_dict = {"name": "Alice", 1: [10, 20, 30], "is_student": True}
print(random_dict)