Some collections should not change, such as the days of a week, while others must look up values by a name, such as a phone book. Tuples and dictionaries serve these two needs.

Tuples

A tuple is an ordered collection written in round brackets, such as t = (1, 2, 5). It is immutable, so its items cannot be changed, added or removed. A tuple with one item needs a trailing comma, as in (5,). Tuples are faster than lists and are safe to use for fixed data. Indexing, slicing, len(), count(), index(), min(), max() and sum() work on tuples. Tuples can be joined with + and repeated with . A tuple can be unpacked* into variables, as in x, y = (3, 4), and a function can return several values as a tuple.

Definition: Tuple. An ordered, immutable collection of items written in round brackets.

Dictionaries

A dictionary stores key-value pairs in curly brackets, such as d = {"name": "Asha", "age": 19}. Values are found by key and not by position, as in d["name"]. Keys must be unique and immutable, such as strings, numbers or tuples, while values can be of any type. New pairs are added by assignment, and existing values are changed in the same way. Dictionaries are mutable.

Common Dictionary Functions

The method get(k, default) returns the value for key k, or the default if the key is absent, and avoids an error. keys(), values() and items() give the keys, the values and the pairs. update(d2) merges another dictionary, pop(k) removes a key and returns its value, and del d[k] deletes a pair. The operator in tests whether a key is present. A for loop over a dictionary visits its keys.

Table 3.2: List, tuple and dictionary compared

Feature List Tuple Dictionary
Brackets [ ] ( ) { }
Mutable Yes No Yes
Access by Index Index Key
Duplicates Allowed Allowed Keys unique

Example 3.2: Counting letters with a dictionary

Problem: Count how many times each letter appears in the word "banana", and show the tuple operations on t = (1, 2, 5, 7, 9, 2).

Solution:

  1. Start with an empty dictionary and, for each letter, add 1 to its count using get().
  2. For the tuple, use count(2), max(), slicing and concatenation.

Result: The counts are b = 1, a = 3 and n = 2, and the tuple contains the value 2 twice.

count = {}
for ch in "banana":
    count[ch] = count.get(ch, 0) + 1
print(count, list(count.items()))
t = (1, 2, 5, 7, 9, 2)
print(t.count(2), max(t), t[1:4], t + (11, 13))
x, y = (3, 4)
print(x + y, len(count), "a" in count)
d = {"name": "Asha", "age": 19}
d["city"] = "Gurugram"
print(d.get("phone", "none"), list(d.keys()))

Output

{'b': 1, 'a': 3, 'n': 2} [('b', 1), ('a', 3), ('n', 2)]
2 9 (2, 5, 7) (1, 2, 5, 7, 9, 2, 11, 13)
7 3 True
none ['name', 'age', 'city']

Common mistakes

  • Writing (5) for a one-item tuple. It needs a comma, as in (5,).
  • Trying to change an item of a tuple, which raises TypeError.
  • Reading a missing key with d[k], which raises KeyError. Use d.get(k).

Key takeaways

  • Tuples are immutable and written with round brackets.
  • Dictionaries store key-value pairs, and keys are unique.
  • get() avoids a KeyError for a missing key.
  • items() gives the pairs of a dictionary.

Practice questions

  1. What is a tuple?
  2. How is a value found in a dictionary?
  3. What does d.get("x", 0) do?

Answers to the practice questions

  1. An ordered, immutable collection of items.
  2. By its key.
  3. Returns the value of key "x", or 0 if the key is missing.

Sources

  • Official BCA syllabus Python Programming, course code 26BCA403SEC01, Unit III