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}67print(person["name"]) # Alice8print(person.get("age")) # 309print(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}23d["c"] = 3 # add4d.update({"d": 4, "e": 5}) # bulk add5del d["a"] # delete key6popped = d.pop("b") # remove & return78print(d)9print(popped)
Output
{'c': 3, 'd': 4, 'e': 5}
203Dictionary Comprehension
Build dictionaries concisely with comprehension syntax.
Python
1squares = {x: x**2 for x in range(6)}2print(squares)34# Invert a dictionary5original = {"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'}