Python Learning Series · @onlysamarrr · Day 18 / 30

Day 18: Dict Methods and Loops

Day 18 covers dict methods: keys() gives all keys, values() gives all values, and items() gives (key, value) pairs. Never add or delete keys while looping over a dict, or you get a RuntimeError.

Phase: Intermediate · Reels: 86/450 – 90/450

Quick Answer

Day 18 covers dict methods: keys() gives all keys, values() gives all values, and items() gives (key, value) pairs. Never add or delete keys while looping over a dict, or you get a RuntimeError.

What You Will Learn

Code

marks = {"Arhan": 92, "Riya": 85, "Aman": 78}
print(list(marks.keys()))
print(list(marks.values()))
print(list(marks.items()))
count = {}
for w in "to be or not to be".split():
    count[w] = count.get(w, 0) + 1
print(count)
print(count["to"])

Output

['Arhan', 'Riya', 'Aman']
[92, 85, 78]
[('Arhan', 92), ('Riya', 85), ('Aman', 78)]
{'to': 2, 'be': 2, 'or': 1, 'not': 1}
2

Code Explained, Line by Line

  1. .keys() returns all keys, .values() returns all values, .items() returns (key, value) pairs.
  2. count.get(w, 0) + 1 is the standard word-count pattern: start from 0 on first sight, then add 1.
  3. Since Python 3.7, dicts remember insertion order: items come out in the order they were added.
  4. Changing a dict during a loop raises RuntimeError. Loop over list(d) if you must change it.
Common Mistake: Do not add or delete keys while looping over a dict. Make a list of keys first, then change the dict.

Real-Life Use

Word counts, vote counts and frequency tables all use this dict pattern.

Practice Task: Count the words in a sentence using a dict and the .get() pattern.

Test Yourself — MCQs

Select (tick) an option, then tap Check answer to see instantly whether your answer is right or wrong, with an explanation. You can change your answer and check again.

Q1. What does .items() return?

Q2. What happens if you add a key while looping over a dict?

Q3. Do dicts remember insertion order in modern Python?

Today's 5 Reels (from the 90-Day Plan Excel)

86/450Conceptkeys, values, items
87/450Live demoget() aur update() demo
88/450Common mistakeLoop mein dict change mat karo
89/450QuizQuiz: word count
90/450Interview / real lifeInterview: dict ordered hai?
← Day 17Day 19 →