Follow Us
माध्यम चुनें / Select Medium:
Eng (English) Hindi (हिन्दी)
CBSE • कक्षा XI • Computer Science • अध्याय 10
अनुमानित समय: 45 Mins
प्रगति: अध्ययनरत

टुपल और डिक्शनरी (Tuples & Dictionaries)

In CBSE Class 11 Computer Science, "Tuples and Dictionaries" provides an exhaustive master resource on immutable records and hash-table key-value mappings in Python. This comprehensive chapter covers tuple immutability, the single-element tuple comma rule, tuple packing and unpacking, dictionary associative key-value mapping architecture, key hashability requirements, dictionary traversal, dynamic updating, and dictionary methods (`keys()`, `values()`, `items()`, `get()`, `update()`, `pop()`, `popitem()`) aligned with the 2026–27 CBSE curriculum.

Why Do Computers Need Both Unchangeable Records and Instant-Lookup Phonebooks?

Consider two different data scenarios in software: First, GPS coordinates for the Taj Mahal (27.1751, 78.0421). You would never want any function to accidentally modify latitude or longitude in memory. Second, a dictionary storing user profiles where you can instantly look up any username among 100 million accounts in less than a microsecond. To solve these dual challenges, Python provides two specialized data structures: Tuples (immutable sequences that guarantee data integrity) and Dictionaries (hash-map key-value stores that deliver O(1) constant-time lookups). How do tuples protect data from accidental corruption, and how do hash functions allow dictionaries to locate values instantaneously? This chapter masters advanced data structures.

यह अध्याय क्यों महत्वपूर्ण है

Tuples and dictionaries are fundamental to professional Python software architecture. Tuples are used everywhere data immutability and memory optimization are required—such as returning multiple values from functions, database query row representations, and dictionary keys. Dictionaries form the backbone of JSON APIs, configuration files, caching layers, and database records. Understanding dictionary hash tables and key immutability requirements is essential for every aspiring backend and data engineer.

अध्ययन से पूर्व (आवश्यक ज्ञान)

  • Lists, mutability vs immutability concepts.
  • Sequence indexing and slicing.
  • Looping constructs: iterating through collections.

इस अध्याय के लक्ष्य

  • Construct tuples and master the single-element comma rule (`t = (5,)` vs `t = (5)`).
  • Apply tuple packing and unpacking to swap variables and process function return values.
  • Explain tuple immutability and why tuples are hashable and valid as dictionary keys.
  • Construct dictionaries using key-value pairs and understand the hashability requirement for keys.
  • Access dictionary elements safely using `d.get(key, default)` to prevent `KeyError` exceptions.
  • Execute dictionary methods: `keys()`, `values()`, `items()`, `update()`, `pop()`, and `clear()`.
  • Traverse key-value pairs simultaneously using `for k, v in d.items():`.

अध्याय रूपरेखा एवं प्रगति

1 1. Tuples: Immutable Ordered Record...
2 2. Dictionaries: Associative Key-Va...
3 3. Dictionary Methods & Iteration A...

सम्पूर्ण सैद्धांतिक एवं वैचारिक अध्ययन

1. Tuples: Immutable Ordered Records

Understand

A Tuple is an immutable, ordered sequence of heterogeneous elements enclosed in parentheses (`(...)`):

The Single-Element Tuple Comma Rule (CRITICAL EXAM TRAP):

Parentheses alone do not make a tuple—parentheses are also used for mathematical grouping. To define a single-element tuple, a trailing comma is mandatory:

t1 = (5)    # NOT a tuple! Evaluates to integer: type(t1) is <class 'int'>
t2 = (5,)   # VALID single-element tuple: type(t2) is <class 'tuple'>
Tuple Packing and Unpacking
# Tuple Packing:
record = "Aarav", 11, 94.5    # Packed into tuple ('Aarav', 11, 94.5)

# Tuple Unpacking:
name, grade, marks = record   # Unpacks into 3 individual variables
print(name, marks)            # Aarav 94.5

2. Dictionaries: Associative Key-Value Mappings

Understand

A Dictionary is a mutable mapping data structure storing unordered (insertion-ordered in modern Python) pairs of `key: value` enclosed in curly braces (`{...}`):

Dictionary Key Requirements (The Hashability Law):
  • Keys Must Be Unique: Duplicate keys are not permitted; assigning to an existing key overwrites its previous value.
  • Keys Must Be Immutable: A key must belong to an immutable data type (`int`, `float`, `str`, `tuple`). A mutable type like a `list` or another `dict` cannot be a key and raises `TypeError: unhashable type: 'list'`!
  • Values Can Be Anything: Values can be mutable or immutable, unique or duplicated.
Safe Element Access: `dict[key]` vs `dict.get(key, default)`
student = {"name": "Sneha", "roll": 101}

# Direct indexing raises KeyError if key is absent:
# print(student["marks"]) # KeyError: 'marks'!

# Safe access with .get():
marks = student.get("marks", 0.0) # Returns 0.0 without crashing!
print(marks) # 0.0

3. Dictionary Methods & Iteration Algorithms

Understand & Reference
MethodActionExample Code
`d.keys()`Returns a view object of all keys.`d.keys()` → `dict_keys(['a', 'b'])`
`d.values()`Returns a view object of all values.`d.values()` → `dict_values([10, 20])`
`d.items()`Returns key-value pairs as a view of tuples.`d.items()` → `dict_items([('a', 10), ('b', 20)])`
`d.update(other)`Merges key-value pairs from `other` into `d`.`d.update({'c': 30})`
`d.pop(key[, default])`Removes `key` and returns its value.`val = d.pop('a')`
`d.popitem()`Removes and returns the last inserted `(key, value)` tuple.`k, v = d.popitem()`
`d.clear()`Empties the dictionary.`d.clear()` → `{}`
Simultaneous Key-Value Traversal:
grades = {"Aarav": 95, "Sneha": 98, "Rohan": 88}
for student, score in grades.items():
    print(f"{student}: {score}")

प्रोग्रामिंग सिंटेक्स, स्टेटमेंट्स एवं भाषा अनुवादक नियम

Dictionary Lookup Complexity
$$O(1) \text{ Average Time Complexity}$$
Hash table indexing enables instantaneous lookups regardless of dictionary size.
Key Hashability Condition
$$\text{hash}(key) \neq \text{Error} \iff key \in \text{Immutable Types}$$
Only hashable immutable objects can serve as dictionary keys.

Tuples vs Dictionaries Architecture Map

Tuples (Immutable) vs Dictionaries (Hash Mappings) Tuples: (item1, item2, ...) Ordered & Immutable Cannot add, delete, or modify elements in-place Single-Element Comma Trap! t = (5) → int t = (5,) → tuple Dictionaries: {key: value} Key (Hash) Value Key Rules (Hashability Law) Keys MUST be unique & immutable (str, int, tuple) Lists CANNOT be keys! (Unhashable type) Methods .get(key, default) • .keys() • .values() • .items() .update() • .pop(key) • .clear()

अध्याय का सार संक्षेप एवं 10 मुख्य निष्कर्ष

मुख्य बिंदु 1
A tuple is an ordered, immutable sequence of heterogeneous elements enclosed in parentheses `(...)`.
मुख्य बिंदु 2
A single-element tuple requires a trailing comma: `t = (5,)`; omitting the comma creates an integer `(5)`.
मुख्य बिंदु 3
Tuple packing groups values into a tuple; tuple unpacking extracts values into individual variables.
मुख्य बिंदु 4
Because tuples are immutable, they are hashable and can serve as dictionary keys.
मुख्य बिंदु 5
A dictionary is a mutable, associative mapping of `key: value` pairs enclosed in curly braces `{...}`.
मुख्य बिंदु 6
Dictionary keys must be unique and immutable (`int`, `str`, `tuple`); values can be of any data type.
मुख्य बिंदु 7
Using a mutable type (such as a list) as a dictionary key raises a `TypeError: unhashable type: 'list'`.
मुख्य बिंदु 8
The `get(key, default)` method accesses values safely without triggering a `KeyError` if the key is absent.
मुख्य बिंदु 9
`d.keys()`, `d.values()`, and `d.items()` return dynamic view objects of keys, values, and `(key, value)` tuples.
मुख्य बिंदु 10
Dictionary lookups operate in $O(1)$ average time complexity due to internal hash table indexing.

स्व-मूल्यांकन अभ्यास (Check Your Understanding)

मूल वैचारिक स्पष्टता की जांच के लिए नैदानिक प्रश्न। पहले स्वयं हल करें, फिर उत्तर देखें।

1
Explain why `t = (10)` is not a tuple in Python, while `t = (10,)` is. How does Python interpret `t = (10)`?
उत्तर एवं व्याख्या देखें
उत्तर: In Python, parentheses are used for mathematical expression grouping (operator precedence). When Python sees `t = (10)`, it interprets the parentheses as mathematical grouping around the integer 10, resulting in `type(t)` being ``. To disambiguate and declare a single-element tuple, Python requires a trailing comma: `t = (10,)`.
Parentheses without a comma denote algebraic grouping; a comma creates a tuple.
2
Can a list be used as a key in a Python dictionary? Can a tuple? Explain using Python's hashability rules.
उत्तर एवं व्याख्या देखें
उत्तर: A list CANNOT be used as a dictionary key; doing so raises a `TypeError: unhashable type: 'list'`. This is because dictionary keys must be hashable—their hash value must remain constant throughout their lifetime. Because lists are mutable, their contents can change, which would corrupt the hash table. In contrast, a tuple containing only immutable elements is immutable and hashable, making it completely valid as a dictionary key.
Dictionary keys must be hashable and immutable; lists are mutable so cannot be keys.
3
Predict the output of the following code:
d = {"A": 1, "B": 2}
print(d.get("C", 100))
print(d.get("A", 100))
print(d["A"])
उत्तर एवं व्याख्या देखें
उत्तर: Output:
100
1
1
Explanation: `"C"` is not in `d`, so `get("C", 100)` returns the default value `100`. `"A"` exists with value `1`, so `get("A", 100)` returns `1` (default ignored). `d["A"]` directly returns `1`.
get() returns value if key exists, otherwise returns the specified default.
4
What is tuple unpacking? Demonstrate how to swap two variables `a` and `b` in a single line using tuple unpacking.
उत्तर एवं व्याख्या देखें
उत्तर: Tuple unpacking is the process of extracting the individual elements of a tuple directly into multiple distinct variables in a single statement.
Variable swapping:
a, b = b, a
Explanation: Python first evaluates the right side, packing `(b, a)` into a temporary tuple in memory. It then unpacks that tuple into the variables on the left side, swapping their values simultaneously without needing a temporary third variable.
a, b = b, a packs right-hand values into a temporary tuple, then unpacks into left.
5
Given the dictionary `scores = {"Rohan": 85, "Aarav": 92}`, write code to add "Sneha" with 96, update "Rohan" to 89, and remove "Aarav".
उत्तर एवं व्याख्या देखें
उत्तर:
scores = {"Rohan": 85, "Aarav": 92}
scores["Sneha"] = 96      # Adds new key "Sneha"
scores["Rohan"] = 89      # Updates existing key "Rohan"
scores.pop("Aarav")       # Removes key "Aarav"
print(scores)             # {'Rohan': 89, 'Sneha': 96}

Assignment adds or updates; .pop(key) removes a key-value pair.
6
How do you iterate through a dictionary to print each key and its corresponding value? Write a code snippet using `.items()`.
उत्तर एवं व्याख्या देखें
उत्तर:
student = {"name": "Priya", "age": 16, "city": "Kolkata"}
for key, value in student.items():
    print(f"{key} -> {value}")

for key, value in d.items(): iterates through unpacked key-value pairs.
7
What is the output of the following dictionary code?
d = {1: "One", 2: "Two"}
d[1] = "First"
d[True] = "TrueValue"
print(d)
उत्तर एवं व्याख्या देखें
उत्तर: Output: `{1: 'TrueValue', 2: 'Two'}`
Explanation: In Python, `bool` is a subclass of `int`. The Boolean literal `True` evaluates to numeric integer `1` (in fact, `1 == True` is `True` and `hash(1) == hash(True)`). Therefore, `d[True]` points to the exact same key as `d[1]`, overwriting its value with `"TrueValue"`.
In Python, True equals integer 1; assigning to d[True] overwrites d[1].
8
Explain the difference between `d.pop(key)` and `del d[key]`.
उत्तर एवं व्याख्या देखें
उत्तर: Both remove the key-value pair from dictionary `d`. However, `d.pop(key)` returns the removed value (and allows an optional default value to prevent errors if the key is missing: `d.pop(key, default)`). In contrast, `del d[key]` is a Python statement that deletes the key in-place, returns nothing, and strictly raises a `KeyError` if the key is absent.
pop() returns the removed value and supports defaults; del returns nothing.
अध्याय का अध्ययन पूर्ण हुआ?
अभ्यास के लिए तैयार?

ऑनलाइन CBT टेस्ट देकर तैयारी का मूल्यांकन करें

झारखण्ड बोर्ड परीक्षा पैटर्न पर आधारित बहुविकल्पीय प्रश्नों का ऑनलाइन टेस्ट दें। तुरंत परिणाम, समय विश्लेषण और प्रत्येक प्रश्न का विस्तृत हल प्राप्त करें।

AI अध्ययन मित्र

त्वरित शंका समाधान

टुपल और डिक्शनरी (Tuples & Dictionaries) में कोई संदेह या प्रश्न है? हमारे AI अध्ययन मित्र से तुरंत समझें।