beginnerData Structures

Dictionaries

Key-value mappings for fast lookups and structured data.

01Creating & Accessing

Dictionaries store key-value pairs. Keys must be unique and hashable.

Python
1person = {
2 "name": "Alice",
3 "age": 30,
4 "city": "New York"
5}
6
7print(person["name"]) # Alice
8print(person.get("age")) # 30
9print(person.get("job", "N/A")) # N/A (default)
Output
Alice
30
N/A

02Modifying Dictionaries

Add, update, and remove key-value pairs.

Python
1d = {"a": 1, "b": 2}
2
3d["c"] = 3 # add
4d.update({"d": 4, "e": 5}) # bulk add
5del d["a"] # delete key
6popped = d.pop("b") # remove & return
7
8print(d)
9print(popped)
Output
{'c': 3, 'd': 4, 'e': 5}
2

03Dictionary Comprehension

Build dictionaries concisely with comprehension syntax.

Python
1squares = {x: x**2 for x in range(6)}
2print(squares)
3
4# Invert a dictionary
5original = {"a": 1, "b": 2, "c": 3}
6inverted = {v: k for k, v in original.items()}
7print(inverted)
Output
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{1: 'a', 2: 'b', 3: 'c'}