Mastering Python Dictionaries: A Complete Guide with Examples and Practice

 3 min read

YouTube video ID: NlZ40LHp2IY

Source: YouTube video by Aakash SinghWatch original video

PDF

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

OperationSyntaxDescription
Lengthlen(colors)Number of key‑value pairs
Keys listcolors.keys()Returns a view of all keys
Values listcolors.values()Returns a view of all values
Items listcolors.items()Returns a view of (key, value) tuples
Clear allcolors.clear()Empties the dictionary
Delete a pairdel 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)

  1. Creating an empty dictionary – both {} and dict() are correct.
  2. Key uniqueness – keys must be unique; values may repeat.
  3. Access method – dictionaries use keys, not numeric indexes.
  4. Mutable nature – you can change values or add new keys after creation.
  5. Error handling – accessing a missing key raises KeyError; use get() 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 pairs
  • dict.clear(): empty dictionary
  • dict.get(key, default): safe retrieval
  • dict.items(): view of (key, value) tuples
  • dict.keys(), dict.values(): views of keys or values
  • dict.update(other_dict): merge dictionaries
  • del dict[key]: delete a specific entry
  • max(dict, key=dict.get), min(dict, key=dict.get): find keys with extreme values

Practice Questions

  1. What will print(colors[0]) output? (Answer: KeyError – dictionaries are not indexed by numbers.)
  2. Given d = {"A":1, "B":2, "C":3}, what does d.get("D", 0) return? (Answer: 0)
  3. After d.update({"B":5, "D":4}), what is d? (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.

PDF