Tuples are immutable sequences and dictionaries store key: value pairs. Their operations, methods and traversal, and counting with a dictionary.
| One-item tuple | type((5)) is int; type((5,)) is tuple, and it prints as (5,) |
| Tuple operations | (1, 2) + (3,) = (1, 2, 3); (0,) * 3 = (0, 0, 0); sorted((3, 1, 2)) = [1, 2, 3] |
| Changing a dictionary | d = {'a': 1}; d['b'] = 2 gives {'a': 1, 'b': 2}; del d['a'] leaves {'b': 2} |
| Methods | d.get(k, 0); d.pop(k) gives the value; d.popitem() removes the last pair, as a tuple |
| Views print as | dict_keys(['a', 'b']); dict_items([('a', 1), ('b', 2)]) |
| len and max | len(d) counts the pairs; max(d) compares the keys; max(d.values()) the values |
| Counting | d = {} for ch in 'banana': d[ch] = d.get(ch, 0) + 1 print(d) # {'b': 1, 'a': 3, 'n': 2} |
What does this program print?
d = {'pear': 70, 'lemon': 68, 'peach': 60}
d['plum'] = 89
d['pear'] = d['pear'] + 10
del d['peach']
print(d)
Working: a new key goes at the end; changing a value keeps its place
Answer: {'pear': 80, 'lemon': 68, 'plum': 89}