~2 min read • Updated Jul 18, 2025

Defining a Dictionary


Dictionaries use curly braces {} and consist of key–value pairs:



my_dict = {"name": "Ali", "age": 25, "is_active": True}
empty_dict = {}
mixed_keys = {1: "one", True: "yes", 3.14: "pi"}

Key Features of Dictionaries


  • Keys must be immutable: such as strings, numbers, or tuples
  • Values can be of any type: including other dictionaries
  • Keys are unique: duplicate keys overwrite previous values
  • Insertion order preserved (Python 3.7+)

Accessing and Modifying Values



person = {"name": "Zara", "city": "Doha"}

print(person["name"])         # 'Zara'
person["age"] = 30            # Adds new key
person["city"] = "Dubai"      # Modifies value

Common Dictionary Methods


MethodDescription
get(key, default)Returns value of key or default
keys()Returns all keys
values()Returns all values
items()Returns all key–value pairs
update(dict2)Merges another dictionary
pop(key)Removes key and returns value
popitem()Removes and returns last item
clear()Empties the dictionary
copy()Returns a shallow copy

Usage Examples:



user = {"username": "shahin", "role": "admin"}

print(user.get("email", "not found"))     # 'not found'
print(user.keys())                        # dict_keys(['username', 'role'])
print(user.values())                      # dict_values(['shahin', 'admin'])
user.update({"email": "[email protected]"})
print(user.pop("role"))                   # 'admin'
print(user)                               # {'username': 'shahin', 'email': '[email protected]'}

Nested Dictionaries and Iteration



data = {
    "user": {"name": "Ali", "age": 27},
    "status": {"online": True, "verified": False}
}

for section, info in data.items():
    print(section, info)

Conclusion


Dictionaries are essential structures for managing key–value mappings in Python. With fast lookups, flexible value types, and a rich method set, they excel at storing dynamic or nested data and powering associative logic in applications.


Written & researched by Dr. Shahin Siami