Worksheets › Class 11 › Tuples and Dictionaries › Cheat sheet
Class 11 Tuples and Dictionaries: cheat sheet
CBSE Computer Science. Tuples are immutable sequences and dictionaries store key: value pairs. Their operations, methods and traversal, and counting with a dictionary.
Key ideas
- A tuple is written with commas, usually inside brackets; a one-item tuple needs a comma, (5,), since (5) is just the int 5.
- Tuples are immutable: T[0] = 1 is a TypeError, but indexing, slicing, + and * work, and a slice of a tuple is a tuple.
- In a, b = b, a the right side is worked out first; the number of names must match the number of values, or there is a ValueError.
- Keys are unique and immutable (numbers, strings, tuples); d[k] gives the value, a missing key is a KeyError, and d.get(k) gives None instead.
- Giving a value to an existing key changes it where it is; a new key goes at the end, as dictionaries keep the order of insertion.
- A for loop over a dictionary gives its keys; keys(), values() and items() give views, and items() gives (key, value) tuples.
Remember
| 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} |
Watch out
- Writing (5) for a one-item tuple: it needs the comma.
- Expecting a key whose value changes to move to the end: it keeps its place.
- Reading d[k] for a missing key: that is a KeyError; use get().
- Thinking max(d) gives the largest value: it compares the keys.
Worked example
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}
Practise Tuples and Dictionaries
Revise with this page, then practise: every Tuples and Dictionaries sheet in the app is new, with an answer key and working.
Coming soon for Android and iPhone.