Python Dictionaries
⏱ Estimated reading time: 2 min
Python Dictionaries
A dictionary in Python is an unordered collection of key-value pairs. Each key must be unique and immutable, while values can be of any data type. Dictionaries are mutable, meaning you can change their content after creation.
Creating a dictionary:
Example:
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
Empty dictionary:
Example:
empty_dict = {}
or
empty_dict = dict()
Accessing values:
Access values using their keys.
Example:
print(my_dict["name"]) # Alice
print(my_dict.get("age")) # 25
Adding or updating items:
Assign a value to a key to add or update it.
Example:
my_dict["email"] = "alice@example.com
" # add
my_dict["age"] = 26 # update
Removing items:
-
pop(key): removes the key and returns its value
-
popitem(): removes the last inserted key-value pair
-
del: deletes a key or the entire dictionary
-
clear(): removes all items
Example:
my_dict.pop("city")
del my_dict["age"]
my_dict.clear()
Dictionary keys, values, and items:
-
keys(): returns all keys
-
values(): returns all values
-
items(): returns all key-value pairs
Example:
print(my_dict.keys())
print(my_dict.values())
print(my_dict.items())
Iterating through a dictionary:
-
For keys:
for key in my_dict:
print(key) -
For values:
for value in my_dict.values():
print(value) -
For key-value pairs:
for key, value in my_dict.items():
print(key, value)
Nested dictionaries:
A dictionary can contain other dictionaries.
Example:
students = {
"Alice": {"age": 25, "city": "New York"},
"Bob": {"age": 22, "city": "Los Angeles"}
}
print(students["Alice"]["city"]) # New York
Checking if a key exists:
Use the in keyword.
Example:
if "name" in my_dict:
print("Key exists")
Copying a dictionary:
-
copy(): creates a shallow copy
-
dict(): can also create a copy
Example:
new_dict = my_dict.copy()
Register Now
Share this Post
← Back to Tutorials