Dictionaries

Carson West

Python 1 Home

Dictionaries Dictionaries are unordered collections of key-value pairs. Keys must be immutable (like strings, numbers, or tuples), while values can be of any data type.

my_dict = {"name": "Alice", "age": 30, "city": "[New York](./../new-york/)"}
print(my_dict["name"]])  # Accessing values using keys

Accessing a non-existent key raises a KeyError. Use the get() method for safer access:

print(my_dict.get("country", "Unknown")) # Returns "Unknown" if "country" is not found

Adding and modifying entries:

my_dict["occupation"]] = "Engineer"
my_dict["age"]] = 31

Iterating through dictionaries:

for key in my_dict:
    print(key, my_dict[key]])

for key, value in my_dict.items():
    print(key, value)

Other useful methods:

Dictionary Comprehension, Mutable vs Immutable Types