AmbifulWorksheets
Cheat sheet
CBSE · Class 11 · Computer Science

Tuples and Dictionaries

Tuples are immutable sequences and dictionaries store key: value pairs. Their operations, methods and traversal, and counting with a dictionary.

Key ideas

Remember

One-item tupletype((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 dictionaryd = {'a': 1}; d['b'] = 2 gives {'a': 1, 'b': 2}; del d['a'] leaves {'b': 2}
Methodsd.get(k, 0); d.pop(k) gives the value; d.popitem() removes the last pair, as a tuple
Views print asdict_keys(['a', 'b']); dict_items([('a', 1), ('b', 2)])
len and maxlen(d) counts the pairs; max(d) compares the keys; max(d.values()) the values
Countingd = {}
for ch in 'banana':
    d[ch] = d.get(ch, 0) + 1
print(d) # {'b': 1, 'a': 3, 'n': 2}

Watch out

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}