Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
In sequences like lists and tuples, every item is identified strictly by an arbitrary numeric position (0, 1, 2...). But in real-world software, identifying data by index is fragile and unintuitive. When looking up an employee's salary, an Aadhaar user's profile, or a server configuration parameter, you want to query by meaningful semantic labels: "salary", "aadhaar_number", or "database_host".
In Python, the dictionary (dict) is the primary built-in mapping type. A dictionary stores data as associative key-value pairs enclosed in curly braces {key: value}. Under the hood, Python dictionaries are powered by optimized hash tables that deliver lightning-fast $O(1)$ constant-time lookups while guaranteeing insertion-order preservation (since Python 3.7).
+-------------------------------------------------------------------------+
| DICTIONARY REAL-WORLD ANALOGY |
+-------------------------------------------------------------------------+
1. THE KIRANA KHATA BAHI (Ledger of Accounts):
- A local provision store owner in Kanpur maintains a Khata ledger.
- Each customer has a unique account label (The KEY): "Gupta Ji",
"Sharma Niwas", "Dr. Murthy".
- Flipping to "Gupta Ji" reveals their running balance and credit
items (The VALUE).
- Keys must be unique! Two different families cannot share the exact
same Khata account label.
2. THE OXFORD ENGLISH DICTIONARY:
- You search for the term "Algorithm" (KEY).
- You immediately find its meaning, pronunciation, and etymology (VALUE).
- You don't have to read all words starting with 'A' to find "Algorithm".
3. AADHAAR BIOMETRIC DATABASE:
- Key: "9876-5432-1098" (Immutable, strictly unique Aadhaar number)
- Value: {"name": "Priya Sharma", "dob": "1994-08-15", "city": "Jaipur"}
+-------------------------------------------------------------------------+Since Python 3.6+ (officially standardized in 3.7), Python employs a space-efficient, compact hash table architecture that preserves element insertion order while maintaining $O(1)$ access speed.
How data and code flow step-by-step
Python offers several intuitive syntaxes to define dictionaries:
While values can be of any data type whatsoever (numbers, strings, lists, or even other dictionaries), keys must satisfy two strict rules:
str, int, float, tuple, frozenset). Mutable objects like list or dict cannot be keys!Prior to Python 3.7, dictionaries were unordered hash collections where iteration order was unpredictable. In modern Python, dictionaries strictly preserve insertion order:
| Scenario | ❌ Anti-Pattern | ✅ Pythonic Idiom |
|---|---|---|
| Empty Dict | d = dict() | d = {} (Faster literal) |
| Mutable Key | Using a list as key { [1, 2]: "val" } | Using a tuple as key { (1, 2): "val" } |
| Check Key Presence | if k in d.keys(): (Redundant method call) | if k in d: (Direct $O(1)$ dict lookup) |
| Duplicate Keys | Relying on duplicate keys to store history | Store lists as values: { "apples": [50, 75] } |
| Lookups | Looping through dictionary to find a key | Direct index d[key] or safe d.get(key) |
+---------------------------------------------------------------------------+
| PYTHON DICTIONARY CHEAT SHEET |
+---------------------------------------------------------------------------+
| Property | Behavior / Constraint |
|----------------------+----------------------------------------------------|
| Syntax | {key1: val1, key2: val2} |
| Empty Definition | {} or dict() |
| Key Requirements | Must be strictly unique and hashable (immutable) |
| Value Requirements | Completely unconstrained (Any Python object) |
| Ordering | Strictly preserves insertion order (Python 3.7+) |
| Lookup Complexity | O(1) average constant time (Hash table buckets) |
| Duplicate Keys | Later key silently overwrites previous value |
| Membership Test | 'key' in dict tests if key exists |
+---------------------------------------------------------------------------+Accessing dict[key] directly raises a KeyError if the key is missing. Use .get() instead:
Keys must be hashable and immutable. Lists cannot be used as keys, but tuples can:
A. Binary Search Tree B. Compact Hash Table with sparse indices and dense entries C. Linked List of tuples D. Heap Queue
d = {"x": 10, "x": 20}?A. Python raises a KeyError B. Both values are preserved in a list {"x": [10, 20]} C. The second value 20 silently overwrites 10, leaving {"x": 20} D. Python raises a SyntaxError
A. str ("username") B. int (104) C. tuple ((1, 2)) D. list ([1, 2])
A. Python 2.7 B. Python 3.0 C. Python 3.7 D. Python 3.12
len({"A": 1, "B": 2, "A": 3})?A. 3 B. 2 C. 1 D. ValueError
Design a grocery store credit ledger program for a Kirana merchant in Lucknow. Store customer names as keys and their current outstanding credit balances in INR as values. Implement features to register new customer balances, look up a customer's balance by name using direct key access, handle coordinate-based store branch caches using tuple keys, and print a formatted summary ledger.
In the next lesson, we will continue your Python learning journey with Accessing & Updating Items (11: Dictionaries).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Nested Sets | Accessing & Updating Items |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.