Dictionary Iteration & Methods

Dictionary iteration allows processing of key-value pairs in structured data. This is essential for data analysis, frequency counting, and complex data transformations.

Iteration Techniques

scores = {"math": 90, "science": 85}
# Iterate keys: for subject in scores
# Iterate items: for subject, score in scores.items()

get() with Default

counts = {}
word = "hello"
counts[word] = counts.get(word, 0) + 1
{"hello": 1}

Counting Pattern

text = "apple"
counts = {}
for char in text:
counts[char] = counts.get(char, 0) + 1
{"a": 1, "p": 2, "l": 1, "e": 1}

This pattern:

  • Initializes empty dictionary
  • Iterates through each item
  • Uses get() with default 0
  • Increments count

Common Errors

# Forgetting get() default
counts[char] += 1 # KeyError if missing
# Modifying dict size during iteration
for k in counts: del counts[k] # RuntimeError

Practical Use: Word Frequency

document = "the quick brown fox jumps over the lazy dog"
word_counts = {}
for word in document.split():
word_counts[word] = word_counts.get(word, 0) + 1
{"the": 2, "quick": 1, "brown": 1, ...}

Your Task: Character Frequency Analysis

For text = "abbccc":

  1. Initialize empty freq dictionary
  2. Iterate through each character
  3. Update counts using get() method
  4. Final result: {'a': 1, 'b': 2, 'c': 3}

Remember: The get() method's default handles missing keys.

Section 1/5Iteration Techniques

Iteration Techniques

get() with Default

Dictionary Iteration & Methods

Dictionary iteration allows processing of key-value pairs in structured data. This is essential for data analysis, frequency counting, and complex data transformations.

Iteration Techniques

scores = {"math": 90, "science": 85}
# Iterate keys: for subject in scores
# Iterate items: for subject, score in scores.items()

get() with Default

counts = {}
word = "hello"
counts[word] = counts.get(word, 0) + 1
{"hello": 1}

Output:

Click "Check" to run your code.