Dictionary Basics

Creating and using dictionaries

Interview Relevant: Key-value storage

Dictionary Basics

Dictionaries store key-value pairs with O(1) lookup.

Code Examples

Basic dictionary operations.

python
1# Create dictionaries
2empty = {}
3person = {"name": "Alice", "age": 25}
4from_pairs = dict([("a", 1), ("b", 2)])
5from_kwargs = dict(name="Alice", age=25)
6
7# Access values
8person["name"]      # "Alice"
9person.get("name")  # "Alice"
10person.get("city", "Unknown")  # Default if missing
11
12# Modify
13person["age"] = 26
14person["city"] = "NYC"
15
16# Delete
17del person["city"]
18person.pop("age")  # Returns and removes
19
20# Check key exists
21"name" in person  # True
22
23# Length
24len(person)

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In