What You Will Learn
Intermediate
- All dictionary methods
- setdefault and defaultdict
- Common dict patterns
Terminalpython
# setdefault - get or set a default
word_count = {}
for word in ["apple", "banana", "apple", "cherry", "apple"]:
word_count[word] = word_count.setdefault(word, 0) + 1
print(word_count) # {'apple': 3, 'banana': 1, 'cherry': 1}
# update - merge another dict
d1 = {"a": 1, "b": 2}
d2 = {"b": 3, "c": 4}
d1.update(d2)
print(d1) # {'a': 1, 'b': 3, 'c': 4}
# fromkeys - create dict from keys
defaults = dict.fromkeys(["a", "b", "c"], 0)
print(defaults) # {'a': 0, 'b': 0, 'c': 0}Practical Exercise
Use setdefault to count word occurrences
Merge two dicts with update()
Create a dict with fromkeys(['x','y'], 0)
Check if key exists: 'name' in person
Key Takeaways
- setdefault: get value or set default in one operation.
- update(): merge another dictionary.
- fromkeys(): create dict with default values.
- in checks key existence.
- Defaultdict (from collections) auto-creates missing keys.
Comments
Comments
Post a Comment