ЁЯФм
ЁЯзм
ЁЯФн
ЁЯкР
ЁЯзк
тЖР Back to Dashboard
Font Size:

1. Introduction

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.

2. Creating Tuples

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'>

3. Accessing Tuple Elements

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

4. Tuple Immutability

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

5. Why Use Tuples?

Even though tuples offer fewer operations than lists, they have several advantages:

6. Creating Dictionaries

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:

7. Accessing Dictionary Values

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

8. Modifying Dictionaries

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 = {}

9. Traversing a Dictionary

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)

10. Built-in Functions for Tuples and Dictionaries

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]

11. Sample Programs

11.1 Count Word Frequencies Using a Dictionary

text = "apple banana apple mango banana apple"
words = text.split()
freq = {}
for word in words:
    freq[word] = freq.get(word, 0) + 1
print(freq)

11.2 Swap Keys and Values of a Dictionary

d = {"a": 1, "b": 2, "c": 3}
swapped = {value: key for key, value in d.items()}
print(swapped)     # {1: 'a', 2: 'b', 3: 'c'}

11.3 Find the Largest Value in a Dictionary

marks = {"Aarav": 85, "Meera": 92, "Karan": 78}
topper = max(marks, key=marks.get)
print("Topper:", topper)

Quick Revision Tables

Table 1: Tuple vs List

Feature Tuple List
Syntax ( ) [ ]
Mutable No Yes
Methods Only count, index append, pop, sort, etc.
Dictionary key Allowed Not allowed
Speed Faster Slower

Table 2: Common Dictionary Methods

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()

Mind Map

flowchart TD A[Tuples and Dictionaries] --> B[Tuples] B --> B1[Parentheses] B --> B2[Immutable] B --> B3[Indexing and Slicing] B --> B4[count index] B --> B5[Dictionary keys allowed] A --> C[Dictionaries] C --> C1[Curly braces] C --> C2[Key-value pairs] C --> C3[Keys unique and immutable] C --> C4[Access d[key]] C --> C5[Methods keys values items get update pop] A --> D[Comparison] D --> D1[Tuple is read-only list] D --> D2[Dict is a mapping]

Important Diagrams (SVG)

Diagram 1: Tuple vs Dictionary Structure

Tuples and Dictionaries at a Glance TUPLE t = (10, 20, 30) Immutable (read-only) Indexed by position t[0] = 99 -> Error Methods: count, index Can be a dict key Faster than lists DICTIONARY d = {\"name\": \"Meera\"} Key-value mapping Accessed by key, not index Mutable: add, update, delete Keys must be immutable Methods: keys values items Very fast key lookup Golden Rule: Tuples store fixed data by position; dictionaries store data by unique immutable keys.

Diagram 2: Dictionary Operations Flow

Working with a Dictionary Create: d = {\"a\": 1, \"b\": 2} Key-value pairs in braces Access: d[\"a\"] -> 1 Or d.get(\"a\", default) Modify: d[\"c\"] = 3, del d[\"a\"] Add, update, delete entries Inspect: keys(), values(), items() for k, v in d.items() Golden Rule: Never use d[key] for a possibly-missing key; use get() with a default to avoid KeyError.

Common Mistakes

  1. Forgetting the comma in a single-element tuple: (5) is just the integer 5, but (5,) is a tuple.
  2. Trying to modify a tuple: t[0] = 99 raises a TypeError because tuples are immutable.
  3. Using a list as a dictionary key: Keys must be immutable, so [1, 2] as a key raises a TypeError, while (1, 2) works.
  4. Accessing a missing key with d[key]: This raises a KeyError; use get(key, default) instead.
  5. Using parentheses for a dictionary: Dictionaries use curly braces { }; parentheses create tuples.
  6. Forgetting that dictionary keys must be unique: Repeating a key silently overwrites the earlier value.
  7. Confusing items() and values(): items() returns key-value pairs, values() returns only the values.
  8. Calling list methods on tuples: Methods like append() and sort() do not exist for tuples.

Exam Tips

  1. Memorise the tuple vs list differences (syntax, mutability, available methods, use as keys); it is a favourite comparison question.
  2. Know the rules of dictionary keys: unique and immutable.
  3. Remember the get() method with its default value; it is frequently examined for avoiding KeyError.
  4. List the dictionary methods keys(), values(), items(), update(), pop(), get(), clear() with a one-line description of each.
  5. Practise programs that count word frequencies and swap keys with values using dictionary comprehension.
  6. Remember that len(dict) gives the number of key-value pairs.
  7. Be able to iterate a dictionary with for name, score in d.items().

Conclusion

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.