Tuples and dictionaries are two more essential data types in Python. A tuple is an immutable sequence, written with parentheses, that behaves like a read-only list. Once created, a tuple cannot be changed: no element can be added, removed or modified. This immutability makes tuples useful for representing fixed collections of data, such as the coordinates of a point, the name and roll number of a student, or the days of a week, and for use as keys in dictionaries.
A dictionary is a mapping from keys to values, written with curly braces as comma-separated key-value pairs. Unlike sequences, dictionaries are unordered in the traditional sense; elements are accessed not by position but by their unique keys. A dictionary might store a student's marks against their name, a word against its meaning, or a country against its capital. Because keys are hashed, dictionary access is very fast, making dictionaries one of the most powerful and widely used structures in Python.
This chapter explores tuple creation, indexing, slicing and operations; the reasons to prefer tuples over lists; and then dictionaries in depth: creation, accessing values, the get() method, updating and deleting entries, iteration, and the built-in functions and methods such as keys(), values(), items() and update(). Together, tuples and dictionaries complete the student's toolkit of basic data structures.
A tuple is created by enclosing comma-separated values in parentheses.
point = (3, 4)
student = ("Aarav", 16, "Class 11")
single = (5,)
empty = ()
mixed = (10, "Hello", 3.14, True)
Important points:
t = 10, 20, 30 # also a tuple
print(t) # (10, 20, 30)
print(type(t)) # <class 'tuple'>
Tuples use the same indexing and slicing rules as lists and strings. Indexing returns an element; slicing returns a new tuple.
t = (10, 20, 30, 40)
print(t[0]) # 10
print(t[-1]) # 40
print(t[1:3]) # (20, 30)
Because tuples are sequences, the operators + (concatenation), * (repetition) and in (membership) all work.
print((1, 2) + (3, 4)) # (1, 2, 3, 4)
print((0,) * 3) # (0, 0, 0)
print(2 in (1, 2, 3)) # True
The defining property of a tuple is that it is immutable. Attempting to modify a tuple raises a TypeError.
t = (1, 2, 3)
# t[0] = 99 # TypeError: 'tuple' object does not support item assignment
Tuples support read-only operations such as len(), max(), min(), sum(), count() and index(), but none of the modifying methods that lists have (append, insert, remove, pop, sort, etc.).
t = (5, 3, 8, 3)
print(len(t)) # 4
print(max(t)) # 8
print(t.count(3)) # 2
print(t.index(8)) # 2
Even though tuples offer fewer operations than lists, they have several advantages:
A dictionary is an unordered collection of key-value pairs, enclosed in curly braces. Each key is separated from its value by a colon.
student = {"name": "Meera", "roll": 12, "marks": 92}
empty_dict = {}
phone = {"Aarav": 9812345678, "Meera": 9876543210}
Rules for dictionaries:
Values are accessed using their keys in square brackets. The keys() method returns all keys, values() all values, and items() all key-value pairs.
marks = {"Aarav": 85, "Meera": 92, "Karan": 78}
print(marks["Meera"]) # 92
print(list(marks.keys())) # ['Aarav', 'Meera', 'Karan']
print(list(marks.values())) # [85, 92, 78]
print(list(marks.items())) # [('Aarav', 85), ('Meera', 92), ('Karan', 78)]
Accessing a key that does not exist with square brackets raises a KeyError. The safer method is get(key, default), which returns the default value instead of raising an error.
marks = {"Aarav": 85}
print(marks.get("Meera", "Not found")) # Not found
print(marks.get("Aarav", 0)) # 85
Dictionaries are mutable, so entries can be added, updated and removed.
marks = {"Aarav": 85}
marks["Meera"] = 92 # add a new entry
marks["Aarav"] = 90 # update an existing entry
del marks["Aarav"] # delete an entry
marks.update({"Karan": 78, "Neha": 88}) # add multiple entries
print(marks)
The del statement removes a key-value pair. The pop(key) method removes and returns the value for a key. The clear() method removes all entries.
d = {"a": 1, "b": 2, "c": 3}
value = d.pop("a") # value = 1, d = {'b': 2, 'c': 3}
d.clear() # d = {}
A for loop can iterate over the keys of a dictionary by default, and items() allows iterating over both keys and values.
marks = {"Aarav": 85, "Meera": 92, "Karan": 78}
for name in marks:
print(name, marks[name])
for name, score in marks.items():
print(name, "scored", score)
lst = [1, 2, 3]
t = tuple(lst) # (1, 2, 3)
d = dict([("a", 1), ("b", 2)]) # {'a': 1, 'b': 2}
print(sorted((3, 1, 2))) # [1, 2, 3]
text = "apple banana apple mango banana apple"
words = text.split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
print(freq)
d = {"a": 1, "b": 2, "c": 3}
swapped = {value: key for key, value in d.items()}
print(swapped) # {1: 'a', 2: 'b', 3: 'c'}
marks = {"Aarav": 85, "Meera": 92, "Karan": 78}
topper = max(marks, key=marks.get)
print("Topper:", topper)
| Feature | Tuple | List |
|---|---|---|
| Syntax | ( ) | [ ] |
| Mutable | No | Yes |
| Methods | Only count, index | append, pop, sort, etc. |
| Dictionary key | Allowed | Not allowed |
| Speed | Faster | Slower |
| Method | Action | Example |
|---|---|---|
| keys() | All keys | d.keys() |
| values() | All values | d.values() |
| items() | Key-value pairs | d.items() |
| get(k, d) | Value of k or default | d.get("x", 0) |
| update(d2) | Merge another dict | d.update(d2) |
| pop(k) | Remove and return value | d.pop("x") |
| clear() | Remove all entries | d.clear() |
Tuples and dictionaries round out Python's fundamental data structures. Tuples provide immutable, ordered collections that protect data, operate faster than lists, and can serve as dictionary keys. Dictionaries provide an entirely different model, a mapping from unique immutable keys to values, enabling extremely fast lookups and flexible record-keeping. Together they handle both fixed records and associative data efficiently. With all the core data types and control structures now covered, the final chapter broadens the perspective to the societal impact of computing, examining how these technologies affect our digital lives, safety and ethics.