SyntaxStudy
Sign Up
Python Beginner 7 min read

Dictionary Basics

Dictionary Basics

Dictionaries are mutable, ordered (Python 3.7+) mappings from keys to values. Keys must be unique and hashable.

Creating Dicts

d1 = {"name": "Alice", "age": 30, "active": True}
d2 = dict(name="Bob", age=25)
d3 = dict([("x", 1), ("y", 2)])
empty = {}

Accessing Values

person = {"name": "Alice", "age": 30}
print(person["name"])       # Alice
print(person.get("city"))   # None (no KeyError)
print(person.get("city", "Unknown"))  # Unknown

Adding & Updating

person["email"] = "alice@example.com"  # add
person["age"] = 31                     # update
print(person)

Deleting

del person["email"]
removed = person.pop("age")    # removes and returns
print(removed)   # 31
person.popitem()  # removes last inserted item (3.7+)

Checking Keys

print("name" in person)      # True
print("salary" not in person) # True
Example
inventory = {"apples": 50, "bananas": 30, "oranges": 20}
inventory["grapes"] = 15
inventory["apples"] += 10
del inventory["bananas"]
print(inventory)
print("apples" in inventory)  # True
print(len(inventory))         # 3
Pro Tip

Always use get() when a key might not exist — it returns None (or a default) instead of raising a KeyError.