Mastering Python Dictionaries: A Complete Guide with Examples and Practice
Introduction
Python dictionaries are a fundamental data structure that store key‑value pairs. Think of a real‑world dictionary: you look up a word (the key) to find its meaning (the value). In Python, this concept lets you map unique identifiers to any type of data, making look‑ups fast and intuitive.
Key Characteristics
- Unique Keys: Each key must be unique; duplicate keys are not allowed.
- Values Can Be Any Type: Numbers, strings, lists, other dictionaries, etc.
- Unordered Collection: Prior to Python 3.7 dictionaries were unordered; now they preserve insertion order but should still be treated as unordered for algorithmic purposes.
- Mutable: You can add, modify, or delete entries after creation.
Creating Dictionaries
# Empty dictionary
empty_dict = {}
# or using the dict() constructor
empty_dict = dict()
# Dictionary with initial key‑value pairs
colors = {
"R": "Red",
"G": "Green",
"B": "Blue"
}
Adding and Updating Elements
colors["Y"] = "Yellow" # Add new pair
colors["R"] = "Ruby Red" # Update existing value
You can also use the update() method to merge another dictionary:
more_colors = {"O": "Orange"}
colors.update(more_colors)
Accessing Values
- Direct indexing:
colors["R"]returns "Red". - Using get() to avoid
KeyError:colors.get("P", "Not found"). - Attempting to access a non‑existent key with
colors["P"]raises a KeyError.
Common Operations
| Operation | Syntax | Description |
|---|---|---|
| Length | len(colors) | Number of key‑value pairs |
| Keys list | colors.keys() | Returns a view of all keys |
| Values list | colors.values() | Returns a view of all values |
| Items list | colors.items() | Returns a view of (key, value) tuples |
| Clear all | colors.clear() | Empties the dictionary |
| Delete a pair | del colors["B"] | Removes the entry for key "B" |
Traversing a Dictionary
for key in colors:
print(key, "->", colors[key])
# Or using items()
for key, value in colors.items():
print(key, "maps to", value)
You can also iterate over just the values with colors.values().
Finding Maximum / Minimum Values
marks = {"Physics": 85, "Chemistry": 78, "Math": 92}
max_subject = max(marks, key=marks.get) # Returns "Math"
min_subject = min(marks, key=marks.get) # Returns "Chemistry"
For the highest numeric value itself:
max_score = max(marks.values())
Frequently Asked MCQs (Highlights)
- Creating an empty dictionary – both
{}anddict()are correct. - Key uniqueness – keys must be unique; values may repeat.
- Access method – dictionaries use keys, not numeric indexes.
- Mutable nature – you can change values or add new keys after creation.
- Error handling – accessing a missing key raises
KeyError; useget()to handle gracefully.
Practical Example: State Capitals
state_capitals = {
"Maharashtra": "Mumbai",
"Rajasthan": "Jaipur",
"Karnataka": "Bengaluru"
}
print(state_capitals["Maharashtra"]) # Mumbai
print(state_capitals.get("Himachal", "Not found"))
Attempting state_capitals["Himachal"] would raise a KeyError.
Updating and Deleting
employee = {"name": "Rohit", "post": "Senior Engineer", "age": 32}
employee["salary"] = 300000 # Add new key
employee["age"] = 33 # Update existing key
print(employee)
del employee["post"] # Remove a key‑value pair
print(employee)
Summary of Dictionary Functions
len(dict): count pairsdict.clear(): empty dictionarydict.get(key, default): safe retrievaldict.items(): view of(key, value)tuplesdict.keys(),dict.values(): views of keys or valuesdict.update(other_dict): merge dictionariesdel dict[key]: delete a specific entrymax(dict, key=dict.get),min(dict, key=dict.get): find keys with extreme values
Practice Questions
- What will
print(colors[0])output? (Answer: KeyError – dictionaries are not indexed by numbers.) - Given
d = {"A":1, "B":2, "C":3}, what doesd.get("D", 0)return? (Answer: 0) - After
d.update({"B":5, "D":4}), what isd? (Answer:{"A":1, "B":5, "C":3, "D":4})
Conclusion
Python dictionaries provide a powerful, flexible way to associate unique keys with any type of value. Mastering creation, access, traversal, and built‑in methods equips you to handle real‑world data structures efficiently, from simple look‑ups to complex nested mappings.
Understanding Python dictionaries—unique keys, mutable values, and a rich set of methods—enables fast, readable data handling, making them essential for any Python programmer.
Frequently Asked Questions
Who is Aakash Singh on YouTube?
Aakash Singh is a YouTube channel that publishes videos on a range of topics. Browse more summaries from this channel below.
Does this page include the full transcript of the video?
Yes, the full transcript for this video is available on this page. Click 'Show transcript' in the sidebar to read it.
Helpful resources related to this video
If you want to practice or explore the concepts discussed in the video, these commonly used tools may help.
Links may be affiliate links. We only include resources that are genuinely relevant to the topic.