<DataInsights />
  • 🏠 Home
  • 📊 SQL
  • 🐍 Python
  • 📈 Power BI
  • 📗 Excel
  • 💼 Career
  • 🎯 Interview Q&A
  • 📁 Case Study
  • 📥 Downloads
  • 🚀 My Portfolio
<DataInsights />

Practical Data Analytics tutorials covering SQL, Python, Power BI, Excel and career guidance for aspiring analysts — 100% free.

Topics

  • SQL Tutorials
  • Python Guide
  • Power BI
  • Excel Tips
  • Career Guide

Quick Links

  • 🛠️ All Tools
  • 🗓️ Archive
  • 📬 Contact
  • 🔍 Search
  • Portfolio
  • Kaggle
  • GitHub

Legal & Info

  • About
  • Contact
  • Privacy Policy
  • Disclaimer
  • Terms & Conditions
  • DMCA
  • Sitemap
Copyright © 2026 Data Insights by Jatin Kumar. All Rights Reserved.Built with ❤️ for Data Analysts
Home/Python/Dictionaries Explained: Complete Guide with Exampl...

Dictionaries Explained: Complete Guide with Examples (2026)

A
August 6, 2026 Jatin Kumar 36 min read Python
Data Insights Python Handbook — Part 6

Dictionaries — Complete Deep Dive 📚

Python ki sabse powerful data structure — Dictionaries. Key-value pairs, O(1) lookup, JSON ka foundation. Creation se lekar Counter aur defaultdict tak, 12 topics Basic se Advanced tak. Employee data ke real examples aur interview Q&A ke saath. Data Insights par.

📑 Is Chapter Mein Kya Sikhenge:

  • 🟢 Basic: Introduction, Creating Dicts, Access/Modify values
  • 🟡 Medium: Dict Methods (get, keys, values, items, update, pop)
  • 🟡 Medium: Iteration, Membership, Merging Dicts
  • 🔴 Advanced: Nested Dicts, Dict Comprehension, defaultdict, Counter
  • 🔴 Advanced: Sorting Dicts, JSON Conversion, Real-world patterns
  • 📋 Summary: Dict vs Other Structures Comparison

📊 Sample Data — Employee Dictionary

Is chapter ke saare examples Employee data par based honge. Har employee ek dict hai with key-value pairs.

KeyValue (Jatin)Value (Priya)Value (Rahul)
id101102103
age253028
deptITHRFinance
salary₹50,000₹75,000₹60,000

1. Dictionary Introduction — Definition & Properties 🟢

📘 Definition: A Dictionary is a mutable, ordered (Python 3.7+), and indexed collection of KEY-VALUE pairs. Created using curly braces {key: value} or dict() constructor. Keys must be UNIQUE and HASHABLE (immutable). Values can be anything. Provides O(1) lookup by key — one of the fastest data structures.

🎯 Samjho Hinglish Mein: Dictionary = real duniya ki dictionary jaisi hai! Word (key) dhundo, meaning (value) mil jaati hai. Har key unique hoti hai — do same words nahi ho sakte. Values kuch bhi ho sakti hain — number, string, list, dict. O(1) lookup ki wajah se ULTRA fast — 1 million entries ho ya 10, lookup same time. JSON, config files, NoSQL databases sab dict pe based hain.

📋 Dict Properties:

PropertyValueMeaning
Ordered✅ Yes (3.7+)Insertion order maintain hota hai
Mutable✅ YesAdd/remove/change ho sakta hai
Indexed✅ Key sePosition se nahi, KEY se access
Keys Unique✅ RequiredDuplicate keys nahi ho sakti
Keys Hashable✅ RequiredSirf immutable keys — str, int, tuple
ValuesAnythingDuplicates allowed, any type
Lookup SpeedO(1) ⚡Hash table based — ultra fast
Symbol{ }emp = {"name": "Jatin"}

💻 Quick Example:

# Employee as dictionary
employee = {"id": 101, "name": "Jatin", "age": 25, "dept": "IT", "salary": 50000}
print(employee["name"])    # Jatin (access by key)
print(employee["salary"])  # 50000
print(len(employee))       # 5 (number of key-value pairs)
print(type(employee))      # <class 'dict'>

💬 Interview Q&A:

Q: Dictionary kya hai aur iski key properties kya hain?
Ans: Dictionary Python ki mutable, ordered (3.7+), key-value pair collection hai. Curly braces {} se banate hain. Properties: (1) Keys unique aur hashable (immutable), (2) Values kuch bhi ho sakti hain, (3) O(1) lookup by key — hash-based, (4) Mutable — add/remove/update, (5) Ordered — insertion order maintain (Python 3.7+). JSON, config, database records ka Python equivalent. Real-world mein sabse zyada use hone wali structure.

Q: Dict keys hashable kyu honi chahiye?
Ans: Dict internally HASH TABLE use karta hai — keys ka hash calculate karke direct memory location pe store karta hai. Hash consistent hone ke liye key IMMUTABLE honi chahiye. Immutable types (str, int, float, tuple, frozenset) hashable hain — allowed as keys. Mutable types (list, dict, set) unhashable hain — content change ho sakta hai, hash inconsistent hoga, lookup break ho jaayega. Isliye {[1,2]: "value"} → TypeError, but {(1,2): "value"} works.

2. Creating Dictionaries — Multiple Ways 🟢

📘 Definition: Dicts can be created using curly braces {}, dict() constructor, from list of tuples, using zip(), dict.fromkeys(), or dict comprehension. Empty dict is {} (NOT set — set uses set()).

💻 Examples:

# Example 1: All ways to create a dict
# Method 1: Curly braces (most common)
emp = {"id": 101, "name": "Jatin", "salary": 50000}

# Method 2: dict() constructor with keyword args
emp2 = dict(id=102, name="Priya", salary=75000)

# Method 3:
From list of tuples
data = [("id", 103), ("name", "Rahul"), ("salary", 60000)]
emp3 = dict(data)

# Method 4: Using zip()
keys = ["id", "name", "salary"]

values = [104, "Neha", 55000]
emp4 = dict(zip(keys, values))

# Method 5: dict.fromkeys() — same value for all keys
default_scores = dict.fromkeys(["Jatin", "Priya", "Rahul"], 0)
print(default_scores)  # {'Jatin': 0, 'Priya': 0, 'Rahul': 0}

# Method 6: Empty dict
empty = {}
empty2 = dict()
# Example 2: Mixed value types & nested dicts
# Different value types allowed
employee = {
    "id": 101,                                # int
    "name": "Jatin",                           # str
    "salary": 50000.75,                       # float
    "active": True,                           # bool
    "skills": ["Python", "SQL"],              # list
    "address": {"city": "Delhi", "pin": 110001}  # nested dict!
}
print(employee["address"]["city"])  # Delhi (nested access)
print(employee["skills"][0])      # Python

# Different key types allowed (must be hashable)
mixed_keys = {
    1: "integer key",
    "name": "string key",
    (1, 2): "tuple key",       # tuple works!
    3.14: "float key"
}
# {[1,2]: "list"} → TypeError! list unhashable
# Example 3: List of employees (real-world)
employees = [
    {"id": 101, "name": "Jatin", "dept": "IT", "salary": 50000},
    {"id": 102, "name": "Priya", "dept": "HR", "salary": 75000},
    {"id": 103, "name": "Rahul", "dept": "Finance", "salary": 60000}
]
for emp in employees:
    print(f"{emp['name']} ({emp['dept']}): ₹{emp['salary']}")
⚠️ Common Mistakes:
  • {} empty DICT hai, empty set nahi! Empty set ke liye set().
  • List/dict/set ko key nahi bana sakte — sirf hashable (str, int, tuple, etc.).
  • Duplicate keys allowed nahi — latest value overwrite kar deti hai.

💬 Interview Q&A:

Q: Dict banane ke kitne tarike hain?
Ans: Multiple ways: (1) Curly braces {"a":1}, (2) dict() constructor with kwargs dict(a=1), (3) From list of tuples dict([("a",1)]), (4) Using zip dict(zip(keys, values)), (5) dict.fromkeys(keys, default) — same value for all keys, (6) Dict comprehension {k:v for k,v in items}. Sabse common — curly braces aur zip. Real world mein API response, JSON, database records se dict banate hain.

Q: Do same keys dict mein pass kiye toh kya hoga?
Ans: Latest value hi rakhi jaati hai — koi error nahi. Example: {"a": 1, "a": 2} → {"a": 2}. Dict comprehension mein bhi same — jo baad mein aata hai woh survive karta hai. Isliye careful raho jab dict merge kar rahe ho — {**dict1, **dict2} — same keys ke liye dict2 wali values win karti hain.

3. Access & Modify Values 🟢

📘 Definition: Access values using square brackets dict[key] or safer dict.get(key, default). dict[key] raises KeyError if key not found, get() returns None (or default). Modify by assignment dict[key] = new_value. Add new pair same way. Delete with del dict[key] or pop().

💻 Examples:

# Example 1: Access values
employee = {"id": 101, "name": "Jatin", "salary": 50000}
# Method 1: Square brackets — KeyError if missing!
print(employee["name"])   # Jatin
# print(employee["dept"]) → KeyError: 'dept'

# Method 2: get() — SAFE, returns None if missing
print(employee.get("name"))          # Jatin
print(employee.get("dept"))          # None (no error!)
print(employee.get("dept", "N/A"))   # N/A (custom default)
print(employee.get("salary", 0))     # 50000
# Example 2: Modify & Add values
employee = {"id": 101, "name": "Jatin", "salary": 50000}
# Modify existing key
employee["salary"] = 55000
print(employee["salary"])  # 55000

# Add new key
employee["dept"] = "IT"
employee["age"] = 25
print(employee)  # {'id': 101, 'name': 'Jatin', 'salary': 55000, 'dept': 'IT', 'age': 25}

# setdefault() — add only if key doesn't exist
employee.setdefault("country", "India")   # adds
employee.setdefault("name", "Rahul")      # does nothing (exists)
print(employee["country"])  # India
print(employee["name"])     # Jatin (unchanged)
# Example 3: Delete values
employee = {"id": 101, "name": "Jatin", "age": 25, "salary": 50000}
# del — removes key, no return
del employee["age"]
print(employee)  # {'id': 101, 'name': 'Jatin', 'salary': 50000}

# pop() — removes AND returns value
removed_salary = employee.pop("salary")
print(removed_salary)  # 50000
print(employee)        # {'id': 101, 'name': 'Jatin'}

# pop() with default — safe if key missing
value = employee.pop("missing", "Not Found")
print(value)  # Not Found (no error!)

# popitem() — removes LAST inserted pair (LIFO)
last = employee.popitem()
print(last)   # ('name', 'Jatin')

# clear() — remove all
employee.clear()
print(employee)  # {}
📋 Access Cheat Sheet:
• Confident key exists → dict[key] (fastest)
• Might not exist → dict.get(key, default) (safe)
• Need to remove & use → dict.pop(key)
• Add only if missing → dict.setdefault(key, default)

💬 Interview Q&A:

Q: dict[key] aur dict.get(key) mein kya difference hai?
Ans: dict[key] agar key nahi hai toh KeyError throw karta hai. dict.get(key) safe hai — None return karta hai. dict.get(key, default) — custom default value de sakte ho. Use case: dict[key] jab confident ho key exist karti hai (fastest). dict.get() jab uncertain ho ya default value chahiye. Common pattern: value = data.get("field", 0) — missing field ke liye 0 default.

Q: setdefault() ka use kya hai?
Ans: setdefault(key, default) — agar key exist karti hai toh uski value return karta hai, agar nahi karti toh default value SET karke return karta hai. Use case: dict mein grouping/counting jab default value chahiye ho. Example: counts.setdefault("apple", 0). Modern alternative: defaultdict use karo — cleaner code. But setdefault standard dict ke liye useful hai.

4. Dict Methods — keys(), values(), items() 🟡

📘 Definition: keys() returns all keys as a view. values() returns all values as a view. items() returns all key-value pairs as tuples in a view. These are "view objects" — dynamic, memory-efficient, reflect real-time changes to dict. Can be converted to list if needed.

📋 Overview:

MethodReturnsExample Result
keys()dict_keys viewdict_keys(['id', 'name'])
values()dict_values viewdict_values([101, 'Jatin'])
items()dict_items viewdict_items([('id', 101), ...])

💻 Examples:

# Example 1: keys(), values(), items()
employee = {"id": 101, "name": "Jatin", "dept": "IT", "salary": 50000}
print(employee.keys())     # dict_keys(['id', 'name', 'dept', 'salary'])
print(employee.values())   # dict_values([101, 'Jatin', 'IT', 50000])
print(employee.items())    # dict_items([('id', 101), ...])

# Convert to list
print(list(employee.keys()))    # ['id', 'name', 'dept', 'salary']
print(list(employee.values()))  # [101, 'Jatin', 'IT', 50000]
# Example 2: Iteration with items()
employee = {"id": 101, "name": "Jatin", "dept": "IT", "salary": 50000}
# Iterate keys only (default)
for key in employee:
    print(key)   # id, name, dept, salary

# Iterate values only
for value in employee.values():
    print(value)

# Iterate key-value pairs (MOST USEFUL)
for key, value in employee.items():
    print(f"{key}: {value}")
# id: 101
# name: Jatin
# dept: IT
# salary: 50000
# Example 3: View objects are DYNAMIC (auto-update!)
employee = {"id": 101, "name": "Jatin"}
keys_view = employee.keys()
print(keys_view)  # dict_keys(['id', 'name'])

# Add new key — view automatically updates!
employee["dept"] = "IT"
print(keys_view)  # dict_keys(['id', 'name', 'dept']) ← updated!

# Practical: aggregate operations on values
salaries = {"Jatin": 50000, "Priya": 75000, "Rahul": 60000}
print(f"Total: ₹{sum(salaries.values())}")    # ₹185000
print(f"Max: ₹{max(salaries.values())}")      # ₹75000
print(f"Avg: ₹{sum(salaries.values())/len(salaries):.0f}")  # ₹61667

# Find employee with max salary
top_earner = max(salaries, key=salaries.get)
print(f"Top earner: {top_earner}")  # Priya

💬 Interview Q&A:

Q: keys(), values(), items() ka return type kya hai?
Ans: Ye "view objects" return karte hain — dict_keys, dict_values, dict_items. Ye lists nahi hain — memory-efficient dynamic views hain jo dict ke saath sync rehte hain. Dict update karo, view automatically update ho jaayega. Iteration mein use kar sakte ho directly. List chahiye toh list() se convert karo. Python 2 mein ye lists return karte the — Python 3 mein views (memory optimization).

Q: Dict ko iterate karne ka best tarika kya hai?
Ans: Depends on what you need: (1) Sirf keys → for k in dict: (default). (2) Sirf values → for v in dict.values():. (3) Both → for k, v in dict.items(): — sabse common. items() sabse useful hai kyunki key aur value dono milte hain simultaneously — tuple unpacking se clean code. Performance sab equal hai — items() thoda zyada memory efficient hai than accessing dict[k] in loop.

5. Update & Merge Dicts 🟡

📘 Definition: update(other) merges another dict into current one — modifies in-place. {**d1, **d2} unpacking creates new merged dict. d1 | d2 operator (Python 3.9+) also creates new merged dict. If same keys exist, later dict's values overwrite.

💻 Examples:

# Example 1:
update() — in-place merge
employee = {"id": 101, "name": "Jatin"}
new_info = {"dept": "IT", "salary": 50000}
employee.
update(new_info)
print(employee)
# {'id': 101, 'name': 'Jatin', 'dept': 'IT', 'salary': 50000}

#
Update overwrites existing keys!
employee.
update({"salary": 60000, "city": "Delhi"})
print(employee["salary"])  # 60000 (overwritten)

#
update() with kwargs
employee.
update(age=25, active=True)
print(employee)
# Example 2: Merge — creates NEW dict (original unchanged)
d1 = {"a": 1, "b": 2}
d2 = {"c": 3, "d": 4}
# Method 1: Unpacking (Python 3.5+)
merged = {**d1, **d2}
print(merged)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Method 2: | operator (Python 3.9+) — CLEANEST
merged2 = d1 | d2
print(merged2)  # Same result

# Method 3: |= for in-place merge (Python 3.9+)
d1 |= d2
print(d1)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Conflict — later dict wins!
a = {"name": "Jatin", "salary": 50000}
b = {"salary": 70000, "dept": "IT"}
print({**a, **b})  # {'name': 'Jatin', 'salary': 70000, 'dept': 'IT'}
# Example 3: Real-world — Combining employee data
basic_info = {"id": 101, "name": "Jatin", "age": 25}
job_info = {"dept": "IT", "salary": 50000, "role": "Analyst"}
contact = {"email": "jatin@co.in", "phone": "9999999999"}
# Combine all into complete profile
full_profile = {**basic_info, **job_info, **contact}
print(full_profile)

# Apply defaults + user preferences
defaults = {"theme": "light", "lang": "en", "notifications": True}
user_prefs = {"theme": "dark", "lang": "hi"}
final_settings = {**defaults, **user_prefs}  # user overrides defaults
print(final_settings)
# {'theme': 'dark', 'lang': 'hi', 'notifications': True}
⚠️ Common Mistakes:
  • update() in-place hai — original modify hota hai, None return karta hai.
  • Same keys ke liye — LATER dict wins (right side priority).
  • Nested dicts merge nahi hote automatically — inner dict overwrite ho jaati hai poori!

💬 Interview Q&A:

Q: Do dicts merge karne ke kitne tarike hain?
Ans: Multiple: (1) d1.update(d2) — in-place, original modify. (2) {**d1, **d2} — unpacking, new dict (3.5+). (3) d1 | d2 — merge operator, new dict (3.9+ only). (4) d1 |= d2 — in-place operator (3.9+). Best practice: modern Python mein | operator cleanest hai. Old code compatibility ke liye {**d1, **d2}. Conflict rules: right/later dict wins — same key ke liye.

Q: Nested dicts kaise merge karo properly?
Ans: Standard merge (update, |) nested dicts ko OVERWRITE karta hai — deep merge nahi. Example: {"a":{"x":1}} | {"a":{"y":2}} → {"a":{"y":2}} — inner dict poori replace! Deep merge ke liye recursive function likhna padta hai, ya collections.ChainMap use karo, ya third-party library like deepmerge. Data science mein Pandas DataFrame merge better hai complex nested data ke liye.

6. Membership & Length 🟡

📘 Definition: key in dict checks if key exists — O(1) fast (hash lookup). key not in dict checks absence. Membership check works on KEYS only by default. For values check, use value in dict.values() — O(n) slower. len(dict) returns number of key-value pairs.

💻 Examples:

# Example 1: Membership check
employee = {"id": 101, "name": "Jatin", "dept": "IT", "salary": 50000}
# Check KEYS (default) — O(1) fast!
print("name" in employee)       # True
print("phone" in employee)      # False
print("phone" not in employee)  # True

# Check VALUES — O(n) slower
print("Jatin" in employee.values())  # True
print(50000 in employee.values())    # True

# Length
print(len(employee))  # 4
# Example 2: Safe access patterns
employee = {"name": "Jatin", "dept": "IT"}
# Pattern 1: Check before access
if "salary" in employee:
    print(employee["salary"])
else:
    print("Salary not set")

# Pattern 2: get() with default (cleaner)
salary = employee.get("salary", 0)
print(f"Salary: ₹{salary}")

# Pattern 3: try-except
try:
    print(employee["salary"])
except KeyError:
    print("Key missing!")
# Example 3: Multiple keys check
employee = {"id": 101, "name": "Jatin", "dept": "IT"}
required = ["id", "name", "salary"]
# Check if all required keys present
missing = [k for k in required if k not in employee]
if missing:
    print(f"Missing fields: {missing}")  # ['salary']

# Using set operations (faster for many keys)
required_set = {"id", "name", "salary"}
present_set = set(employee.keys())
missing_set = required_set - present_set
print(missing_set)  # {'salary'}

# Check if ANY of the keys present
optional = ["phone", "email", "name"]
has_any = any(k in employee for k in optional)
print(has_any)  # True (name exists)
📋 Pro Tips:
• key in dict is O(1) — same as set membership, super fast
• value in dict.values() is O(n) — avoid in loops
• Reverse lookup zaroori ho toh reverse dict banao — {v:k for k,v in d.items()}
• Multiple checks ke liye set operations use karo — cleaner aur faster

💬 Interview Q&A:

Q: Dict mein in operator kya check karta hai?
Ans: Default mein x in dict KEYS check karta hai, values nahi. Reason: dict internally hash table hai keys ke liye — key lookup O(1) constant time. Values check karna hai toh x in dict.values() use karo — O(n) linear search. Interview mein trick question hota hai — bahut log confuse ho jaate hain. Practical: 99% cases mein keys hi check karni hoti hai (existence, filter, validation).

Q: Value se key kaise find karo (reverse lookup)?
Ans: Multiple approaches: (1) Loop with items: next(k for k,v in d.items() if v == target). (2) Reverse dict banao: {v:k for k,v in d.items()} — one-time O(n), then O(1) lookups. Warning: agar values duplicate hain, reverse dict mein data loss hoga (later key wins). (3) List of matching keys: [k for k,v in d.items() if v == target] — sab matches. Frequent reverse lookup ho toh dict structure hi redesign karo.

7. Nested Dictionaries 🔴

📘 Definition: A Nested Dictionary is a dict that contains other dicts (or lists) as values. Perfect for representing hierarchical/multi-level data — JSON, database records, tree structures. Access nested values using chained keys: dict[key1][key2]. Use get() for safe deep access.

🎯 Samjho Hinglish Mein: Nested dict = dict ke andar dict. Real-world data mostly hierarchical hoti hai — company mein departments, departments mein employees, employees ki details. Har level pe dict use karo. JSON files, API responses, MongoDB documents sab nested dicts hi hain. Access: company["IT"]["Jatin"]["salary"] — chained keys.

💻 Examples:

# Example 1: Create & access nested dict
company = {
    "IT": {
        "Jatin": {"age": 25, "salary": 50000},
        "Rahul": {"age": 28, "salary": 60000}
    },
    "HR": {
        "Priya": {"age": 30, "salary": 75000}
    }
}
# Chained access
print(company["IT"]["Jatin"]["salary"])   # 50000
print(company["HR"]["Priya"]["age"])       # 30

# Modify nested value
company["IT"]["Jatin"]["salary"] = 55000

# Add new nested entry
company["IT"]["Neha"] = {"age": 26, "salary": 52000}
print(company["IT"].keys())  # dict_keys(['Jatin', 'Rahul', 'Neha'])
# Example 2: Safe deep access with get()
company = {"IT": {"Jatin": {"salary": 50000}}}
# Unsafe — KeyError if any level missing!
# print(company["IT"]["Priya"]["salary"])  → KeyError!

# Safe with get() chaining
salary = company.get("IT", {}).get("Priya", {}).get("salary", 0)
print(salary)  # 0 (safe default, no error)

# Helper function for deep access
def deep_get(d, *keys, default=None):
    for key in keys:
        if isinstance(d, dict) and key in d:
            d = d[key]
        else:
            return default
    return d

print(deep_get(company, "IT", "Jatin", "salary"))       # 50000
print(deep_get(company, "IT", "Priya", "salary", default=0))  # 0
# Example 3: Iterating nested dict
company = {
    "IT": {"Jatin": {"salary": 50000}, "Rahul": {"salary": 60000}},
    "HR": {"Priya": {"salary": 75000}},
    "Finance": {"Neha": {"salary": 55000}}
}
# Iterate all employees across departments
for dept, employees in company.items():
    print(f"\n{dept} Department:")
    for name, details in employees.items():
        print(f"  {name}: ₹{details['salary']}")

# Aggregate: total company salary
total = sum(
    emp["salary"] 
    for dept in company.values() 
    for emp in dept.values()
)
print(f"\nTotal company salary: ₹{total}")  # ₹240000

# Department-wise total
dept_totals = {dept: sum(emp["salary"] for emp in employees.values())
               for dept, employees in company.items()}
print(dept_totals)  # {'IT': 110000, 'HR': 75000, 'Finance': 55000}

💬 Interview Q&A:

Q: Nested dict mein safely deep value kaise access karo?
Ans: Multiple approaches: (1) Chained get(): d.get("a", {}).get("b", {}).get("c", default) — safe but verbose. (2) Try-except: try: value = d["a"]["b"]["c"] except (KeyError, TypeError): value = default. (3) Helper function: Custom deep_get() function. (4) Third-party: python-benedict library d["a.b.c"] — dot notation. (5) Pandas: nested JSON → DataFrame with json_normalize(). Choose based on frequency aur code style.

Q: Nested dict aur DataFrame mein kya difference hai?
Ans: Nested dict: Pure Python, JSON-friendly, flexible structure, good for hierarchical data, config files. But complex operations (filter, groupby, aggregate) mein manual code likhna padta hai. DataFrame: Pandas ka tabular structure, powerful operations built-in, SQL-like queries, statistical functions, plotting. Interconvertible — pd.DataFrame(dict_data), df.to_dict(). Rule: hierarchical/config → dict, tabular/analytical → DataFrame. Bade data pe DataFrame 100x faster hai.

8. Dict Comprehension 🔴

📘 Definition: Dict Comprehension is a concise way to create dictionaries using a single expression. Syntax: {key_expr: value_expr for item in iterable if condition}. Similar to list comprehension but produces dict. Perfect for transforming data, filtering keys/values, and swapping keys-values.

💻 Examples:

# Example 1: Basic dict comprehension
# Squares dict
squares = {x: x**2 for x in range(1, 6)}
print(squares)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# From two lists (like zip)
names = ["Jatin", "Priya", "Rahul"]
salaries = [50000, 75000, 60000]
emp_dict = {name: salary for name, salary in zip(names, salaries)}
print(emp_dict)  # {'Jatin': 50000, 'Priya': 75000, 'Rahul': 60000}

# Transform existing dict values
prices = {"apple": 100, "banana": 40, "mango": 200}
discounted = {k: v * 0.9 for k, v in prices.items()}
print(discounted)  # {'apple': 90.0, 'banana': 36.0, 'mango': 180.0}
# Example 2: With filter condition
salaries = {"Jatin": 50000, "Priya": 75000, "Rahul": 60000, "Neha": 45000}
# High earners only
high_paid = {name: sal for name, sal in salaries.items() if sal > 55000}
print(high_paid)  # {'Priya': 75000, 'Rahul': 60000}

# Give raise to low earners
adjusted = {name: sal * 1.2 if sal < 55000 else sal 
            for name, sal in salaries.items()}
print(adjusted)

# Categorize salaries
categories = {name: "High" if sal > 65000 else "Mid" if sal > 50000 else "Low" 
              for name, sal in salaries.items()}
print(categories)  # {'Jatin': 'Low', 'Priya': 'High', 'Rahul': 'Mid', 'Neha': 'Low'}
# Example 3: Advanced patterns
# Swap keys and values
emp = {101: "Jatin", 102: "Priya", 103: "Rahul"}
reversed_emp = {v: k for k, v in emp.items()}
print(reversed_emp)  # {'Jatin': 101, 'Priya': 102, 'Rahul': 103}

# From list of tuples to dict
data = [("Jatin", "IT"), ("Priya", "HR"), ("Rahul", "Finance")]
name_to_dept = {name: dept for name, dept in data}
print(name_to_dept)

# Count word frequency
text = "data insights python data analysis python"
words = text.split()
freq = {word: words.count(word) for word in set(words)}
print(freq)  # {'data': 2, 'python': 2, 'insights': 1, 'analysis': 1}

# Nested dict comprehension
matrix = {i: {j: i*j for j in range(1, 4)} for i in range(1, 4)}
print(matrix)
# {1: {1:1,2:2,3:3}, 2: {1:2,2:4,3:6}, 3: {1:3,2:6,3:9}}

# Group employees by department
employees = [("Jatin", "IT"), ("Priya", "HR"), ("Rahul", "IT"), ("Neha", "HR")]
dept_groups = {dept: [n for n, d in employees if d == dept] 
               for dept in {d for _, d in employees}}
print(dept_groups)  # {'IT': ['Jatin', 'Rahul'], 'HR': ['Priya', 'Neha']}
📋 When to Use Dict Comprehension:
• Transform existing dict — modify keys/values in one line
• Create dict from two lists — cleaner than dict(zip())
• Filter dict entries with condition
• Swap keys and values (reverse dict)
• Complex nested structures with logic — but keep readable!

💬 Interview Q&A:

Q: Dict comprehension aur normal loop mein performance kaisa hai?
Ans: Dict comprehension typically 20-40% faster hai equivalent for-loop se. Reason: C-level pe optimized hai, method calls (dict.__setitem__) inline honi hain, aur Python interpreter isse single expression optimize karta hai. Loop mein har iteration mein d[k] = v aur possibly conditional logic overhead hoti hai. But readability important hai — complex comprehensions loops se better nahi hote. Rule: simple transformations → comprehension, complex logic → loop.

Q: Dict comprehension se keys-values swap kaise karo?
Ans: One-liner: {v: k for k, v in d.items()}. Warning: agar values duplicate hain toh data loss hoga — dict duplicate keys allow nahi karta, later value wins. Example: {1:"a", 2:"a"} swap → {"a":2} (only one entry). Safe swap for duplicates: {v: [k for k,v2 in d.items() if v2==v] for v in set(d.values())} — value se list of keys. Values hashable honi chahiye — list values ke saath swap fail hoga.

9. defaultdict & Counter — collections Module 🔴

📘 Definition: defaultdict(default_factory) auto-creates default values for missing keys — no KeyError, no manual check. Counter(iterable) counts frequency of items automatically, returns dict subclass with special methods (most_common, etc.). Both from collections module — MUST-KNOW for data analysis.

🎯 Samjho Hinglish Mein: Regular dict mein missing key = KeyError. defaultdict mein missing key = automatic default value (0, empty list, empty set, whatever tum define karo). Grouping aur counting ke liye BEST. Counter = frequency count karne ka superhero — text analysis, log analysis, most-frequent items — one line mein. Data science mein daily use hote hain.

💻 Examples:

# Example 1: defaultdict — group employees by department
from collections import defaultdict

employees = [
    ("Jatin", "IT"), ("Priya", "HR"), ("Rahul", "IT"),
    ("Neha", "Finance"), ("Vikram", "IT")
]
# WITHOUT defaultdict — verbose!
grouped = {}
for name, dept in employees:
    if dept not in grouped:
        grouped[dept] = []
    grouped[dept].append(name)
print(grouped)

# WITH defaultdict — clean!
grouped_clean = defaultdict(list)
for name, dept in employees:
    grouped_clean[dept].append(name)  # auto-creates [] if key missing
print(dict(grouped_clean))
# {'IT': ['Jatin', 'Rahul', 'Vikram'], 'HR': ['Priya'], 'Finance': ['Neha']}

# Default factories: int (0), list ([]), set (set()), dict ({})
counts = defaultdict(int)         # default: 0
groups = defaultdict(list)        # default: []
unique = defaultdict(set)         # default: set()
nested = defaultdict(dict)        # default: {}
custom = defaultdict(lambda: "N/A")  # custom default
# Example 2: Counter — frequency counting
from collections import Counter

# Count attendance
attendance = ["Jatin", "Priya", "Jatin", "Rahul", "Jatin", "Priya"]
counts = Counter(attendance)
print(counts)  # Counter({'Jatin': 3, 'Priya': 2, 'Rahul': 1})

# Most common items
print(counts.most_common(2))  # [('Jatin', 3), ('Priya', 2)]

# Access counts (0 if missing — no error!)
print(counts["Jatin"])   # 3
print(counts["Neha"])    # 0 (missing key = 0, not KeyError!)

# Total count
print(sum(counts.values()))  # 6

# Update counts
counts.update(["Jatin", "Neha"])
print(counts)  # Counter({'Jatin': 4, 'Priya': 2, 'Rahul': 1, 'Neha': 1})
# Example 3: Real-world applications
from collections import defaultdict, Counter

# 1. Word frequency in text
text = "python data analysis python sql data python"
word_count = Counter(text.split())
print(word_count.most_common(3))
# [('python', 3), ('data', 2), ('analysis', 1)]

# 2. Character frequency
char_freq = Counter("programming")
print(char_freq)  # Counter({'g': 2, 'r': 2, 'm': 2, 'p': 1, ...})

# 3. Salary sum by department (defaultdict + int)
employees = [
    ("Jatin", "IT", 50000),
    ("Priya", "HR", 75000),
    ("Rahul", "IT", 60000),
    ("Neha", "Finance", 55000)
]
dept_total = defaultdict(int)
for name, dept, salary in employees:
    dept_total[dept] += salary
print(dict(dept_total))
# {'IT': 110000, 'HR': 75000, 'Finance': 55000}

# 4. Counter arithmetic
c1 = Counter(["a", "b", "a", "c"])
c2 = Counter(["a", "b", "d"])
print(c1 + c2)   # Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1})
print(c1 - c2)   # Counter({'a': 1, 'c': 1})
print(c1 & c2)   # Counter({'a': 1, 'b': 1}) — intersection (min)
print(c1 | c2)   # Counter({'a': 2, 'b': 1, 'c': 1, 'd': 1}) — union (max)
⚡ Pro Tips:
  • defaultdict Regular dict jaisa behave karta hai — just add default factory function
  • Counter[missing_key] = 0 (no KeyError) — but doesn't add key to counter
  • Counter.most_common(n) — top n items by frequency (sorted)
  • Counter supports +, -, &, | operations — powerful for set-like counting

💬 Interview Q&A:

Q: defaultdict vs regular dict — kab kya use karein?
Ans: defaultdict tab use karo jab tumhe missing keys ke liye consistent default value chahiye — grouping, counting, aggregating scenarios. No manual if key not in dict check chahiye. Example: defaultdict(list) for grouping, defaultdict(int) for counting. Regular dict tab use karo jab exact keys pata hain, missing key error handling zaroori hai, ya JSON compatibility chahiye (JSON parse karke regular dict banti hai). defaultdict internally regular dict subclass hai — sab operations same.

Q: Counter kya hai aur kab use karein?
Ans: Counter dict subclass hai jo automatically frequency count karta hai. Counter(iterable) → keys are items, values are counts. Special methods: most_common(n), elements(), subtract(). Use cases: (1) Word frequency in text, (2) Character analysis, (3) Log file analysis (error types count), (4) Product sales counting, (5) Vote counting. Missing keys return 0 (no error). Arithmetic operators (+, -, &, |) bhi support karta hai. from collections import Counter.

10. Sorting Dictionaries 🔴

📘 Definition: Dicts can be sorted by keys or values using sorted() function. sorted(dict) sorts keys by default. Use key=lambda x: x[1] for value-based sort. Result is a list of tuples — convert back to dict if needed. Python 3.7+ dicts preserve insertion order, so sorted dict maintains sort order.

💻 Examples:

# Example 1: Sort by keys
salaries = {"Rahul": 60000, "Jatin": 50000, "Priya": 75000, "Neha": 55000}
# Sort by keys (alphabetical) — returns list of keys
sorted_keys = sorted(salaries)
print(sorted_keys)  # ['Jatin', 'Neha', 'Priya', 'Rahul']

# Sorted dict (by keys)
sorted_dict = {k: salaries[k] for k in sorted(salaries)}
print(sorted_dict)  # {'Jatin': 50000, 'Neha': 55000, 'Priya': 75000, 'Rahul': 60000}

# Descending order
sorted_desc = dict(sorted(salaries.items(), reverse=True))
print(sorted_desc)
# Example 2: Sort by values
salaries = {"Rahul": 60000, "Jatin": 50000, "Priya": 75000, "Neha": 55000}
# Sort by value (ascending)
by_salary_asc = dict(sorted(salaries.items(), key=lambda x: x[1]))
print(by_salary_asc)
# {'Jatin': 50000, 'Neha': 55000, 'Rahul': 60000, 'Priya': 75000}

# Sort by value (descending) — top earners first
by_salary_desc = dict(sorted(salaries.items(), key=lambda x: x[1], reverse=True))
print(by_salary_desc)
# {'Priya': 75000, 'Rahul': 60000, 'Neha': 55000, 'Jatin': 50000}

# Top 3 earners
top_3 = dict(sorted(salaries.items(), key=lambda x: x[1], reverse=True)[:3])
print(top_3)
# Example 3: Sort complex/nested dicts
employees = [
    {"name": "Jatin", "age": 25, "salary": 50000},
    {"name": "Priya", "age": 30, "salary": 75000},
    {"name": "Rahul", "age": 28, "salary": 60000}
]
# Sort by salary
by_sal = sorted(employees, key=lambda e: e["salary"])
for e in by_sal:
    print(f"{e['name']}: ₹{e['salary']}")

# Multi-level sort — by dept, then salary
data = [
    {"name": "Jatin", "dept": "IT", "salary": 50000},
    {"name": "Rahul", "dept": "IT", "salary": 60000},
    {"name": "Priya", "dept": "HR", "salary": 75000}
]
# Sort by dept ascending, then salary descending
multi_sorted = sorted(data, key=lambda x: (x["dept"], -x["salary"]))
for item in multi_sorted:
    print(item)

💬 Interview Q&A:

Q: Dict ko value se sort kaise karo?
Ans: sorted(dict.items(), key=lambda x: x[1]) — items() key-value tuples deta hai, lambda x[1] value pe sort karta hai. Result list of tuples hai — dict banane ke liye dict(sorted(...)). Descending: reverse=True add karo. Multiple criteria: tuple return karo lambda mein — key=lambda x: (x[1], x[0]). Python 3.7+ mein dict order preserve hoti hai, isliye sorted dict order mein rehta hai.

Q: Top N items dict se kaise nikaalein?
Ans: Methods: (1) Sorted + slice: dict(sorted(d.items(), key=lambda x: x[1], reverse=True)[:n]). (2) heapq (efficient): heapq.nlargest(n, d.items(), key=lambda x: x[1]) — better for very large dicts. (3) Counter.most_common(n): agar Counter object hai. heapq method O(n log k) hai where k = top n, sorted method O(n log n). Bade data ke liye heapq preferred. Interview mein dono batao.

11. JSON Conversion & Real-World Patterns 🔴

📘 Definition: JSON (JavaScript Object Notation) is the standard data exchange format — text-based, human-readable, language-independent. Python json module converts between dict ↔ JSON string. json.dumps() dict → JSON string. json.loads() JSON string → dict. json.dump()/json.load() file operations. Perfect for APIs, config files, data storage.

💻 Examples:

# Example 1: dict ↔ JSON conversion
import json

employee = {
    "id": 101,
    "name": "Jatin",
    "skills": ["Python", "SQL"],
    "active": True,
    "salary": 50000
}
# dict → JSON string
json_str = json.dumps(employee)
print(json_str)
# {"id": 101, "name": "Jatin", "skills": ["Python", "SQL"], "active": true, "salary": 50000}

# Pretty printed (indented)
pretty = json.dumps(employee, indent=2)
print(pretty)

# JSON string → dict
data_str = '{"name": "Priya", "age": 30}'
data_dict = json.loads(data_str)
print(data_dict["name"])  # Priya
print(type(data_dict))     # <class 'dict'>
# Example 2: File I/O with JSON
import json

employees = [
{"id": 101, "name": "Jatin", "salary": 50000},
{"id": 102, "name": "Priya", "salary": 75000}
]
# Write dict to JSON file
with open("employees.json", "w") as f:
json.dump(employees, f, indent=2)

# Read JSON file to dict
with open("employees.json", "r") as f:
loaded = json.load(f)
print(loaded[0]["name"])  # Jatin

# JSON type mapping:
# Python  → JSON
# dict    → object
# list    → array
# str     → string
# int     → number
# True    → true
# False   → false
# None    → null
# Example 3: Real-world patterns
from collections import defaultdict, Counter

employees = [
    {"name": "Jatin", "dept": "IT", "salary": 50000},
    {"name": "Priya", "dept": "HR", "salary": 75000},
    {"name": "Rahul", "dept": "IT", "salary": 60000},
    {"name": "Neha", "dept": "Finance", "salary": 55000}
]
# Pattern 1: Group by department
groups = defaultdict(list)
for emp in employees:
    groups[emp["dept"]].append(emp["name"])
print(dict(groups))

# Pattern 2: Convert list to lookup dict (indexed by name)
by_name = {emp["name"]: emp for emp in employees}
print(by_name["Jatin"])  # O(1) lookup by name

# Pattern 3: Aggregate — total salary per dept
totals = defaultdict(int)
for emp in employees:
    totals[emp["dept"]] += emp["salary"]
print(dict(totals))

# Pattern 4: Count occurrences
dept_counts = Counter(emp["dept"] for emp in employees)
print(dept_counts.most_common())

# Pattern 5: Filter + transform
high_earners = {emp["name"]: emp["salary"] 
                for emp in employees if emp["salary"] > 55000}
print(high_earners)
📋 Real-World Uses:
• APIs: REST API responses are JSON — parse to dict, process, respond
• Config: Application settings in JSON — load as dict at startup
• Database: MongoDB, DynamoDB store as JSON/dict natively
• Caching: Redis stores JSON strings — serialize/deserialize
• Data Exchange: Cross-language data transfer via JSON

💬 Interview Q&A:

Q: json.dumps() aur json.dump() mein kya farak hai?
Ans: dumps() (dump-string): Python object → JSON STRING return karta hai. In-memory operation. Use case: API response banana, string manipulation. dump(): Python object → JSON directly FILE mein WRITE karta hai. File object pass karna padta hai. Use case: config file, data persistence. Similarly loads(): string → dict, load(): file → dict. Rule: 's' = string, no 's' = file. Common pattern: with open() as f: json.dump(data, f).

Q: Dict ke saath kaunse collections module tools daily use hote hain?
Ans: Top 4 must-know: (1) defaultdict — auto-default for missing keys (grouping/counting). (2) Counter — frequency counting one-liner. (3) OrderedDict — Python 3.7+ mein regular dict already ordered hai, but explicit ordering ke liye. (4) ChainMap — multiple dicts ko ek jaisa treat karna without merging (config layers). (5) namedtuple — dict alternative for fixed structure. Data science mein defaultdict aur Counter daily use hote hain — data cleaning aur analysis mein game-changers.

12. Dict vs Other Structures — Complete Comparison 📋

📘 Definition: Dict is the most versatile data structure — combines fast lookup (O(1)), key-based access, ordered iteration, and flexible values. Compare with List (order+index), Tuple (immutable ordered), Set (unique unordered) to make the right choice.

📋 Ultimate Comparison Table:

FeatureDict {k:v}List [ ]Tuple ( )Set { }
Access ByKeyIndexIndexNot accessible
Ordered✅ (3.7+)✅✅❌
Mutable✅✅❌✅
DuplicatesKeys:❌ Values:✅✅✅❌
Lookup SpeedO(1) ⚡O(n) 🐢O(n) 🐢O(1) ⚡
MemoryHighMediumLow ⚡High
Symbol{"a":1}[1,2](1,2){1,2}
Use CaseNamed data lookupOrdered collectionFixed recordsUnique items

💻 Same Data — 4 Structures:

# Employee "Jatin" in 4 structures
# LIST — ordered fields, position-based
emp_list = [101, "Jatin", 25, "IT", 50000]
print(emp_list[1])  # Jatin — but which field is [1]? Unclear!

# TUPLE — immutable ordered record
emp_tuple = (101, "Jatin", 25, "IT", 50000)
print(emp_tuple[1])  # Jatin — same problem

# SET — only unique values, no structure
emp_set = {101, "Jatin", 25, "IT", 50000}
# Can't tell which is what! Order unpredictable!

# DICT — named fields, self-documenting! ✅
emp_dict = {"id": 101, "name": "Jatin", "age": 25, "dept": "IT", "salary": 50000}
print(emp_dict["name"])  # Jatin — CLEAR! Field name explicit
# Decision Framework —
When to use what

# USE DICT
when:
# ✅ Named fields chahiye (self-documenting)
# ✅ Fast lookup by identifier (O(1))
# ✅ Key-value mapping (name → data)
# ✅ JSON-like data / API responses
employees_db = {101: {"name": "Jatin", "dept": "IT"}}

# USE LIST
when:
# ✅ Ordered collection of similar items
# ✅ Dynamic — add/remove frequently
# ✅
Order matters, iteration common
attendance = ["Jatin", "Priya", "Rahul"]

# USE TUPLE
when:
# ✅ Fixed record, won't change
# ✅ Multiple return
values
from function
# ✅ Dict key needed
coordinates = (28.6, 77.2)

# USE
SET
when:
# ✅ Unique items only
# ✅ Fast membership check
# ✅
Set operations (union, intersection)
unique_visitors = {"user1", "user2"}
📋 Ultimate Rule of Thumb:
• Named data lookup (fastest) → DICT
• Ordered collection with duplicates → LIST
• Immutable fixed record → TUPLE
• Unique items with fast lookup → SET
• 💡 Dict is the "Swiss Army Knife" of Python — jab confused ho, dict try karo. 90% real-world problems dict se solve ho jaate hain.

💬 Interview Q&A:

Q: Dict aur List of tuples mein se kaunsa better hai lookup ke liye?
Ans: Dict — bahut better! List of tuples mein lookup O(n) — har tuple check karna padta hai. Dict mein O(1) — hash lookup instant. Example: 10000 employees ki list mein "Jatin" dhundhna — list mein worst case 10000 comparisons, dict mein 1 comparison. Bade data pe difference 1000x+ ho sakta hai. Rule: agar identifier se lookup karna hai frequently, list of tuples ko dict mein convert karo: {t[0]: t for t in list_of_tuples}.

Q: Kis situation mein dict wrong choice hoga?
Ans: Dict avoid karo jab: (1) Sequential order most important hai aur naming useless — list use karo (e.g., timestamps, log entries). (2) Memory critical hai — dict overhead zyada, tuple/list better (e.g., embedded systems, huge data). (3) Uniqueness hi main requirement hai without values — set use karo. (4) Immutability zaroori hai — tuple use karo (dict mutable hai). (5) Simple sequence hai jismein position hi matter karti hai (e.g., matrix rows). Dict powerful hai, but overhead bhi hai — right tool for right job.

Next: Python Handbook — Part 7

Agle part mein hum cover karenge: Control Flow — if/elif/else & Loops. Conditional statements, ternary operator, for & while loops, break/continue/pass, nested loops, else with loops, walrus operator, match-case (3.10+) — sab kuch detail mein. Programming ki backbone. Part 6 (Dictionaries), Part 5 (Sets), Part 4 (Tuples), Part 3 (Lists) Data Insights par available hain.

Happy Learning & Keep Coding! 🚀

👤
Jatin Kumar
Data Analyst & Educator

Python, SQL, Power BI aur Excel mein practical tutorials likhta hoon — taaki data analytics seekhna aasan ho. Portfolio: jatinanalytics.co.in

Portfolio LinkedIn GitHub Kaggle All Articles
Share:

💬 Comments (0)

Spam/links allowed nahi hain — respectful comments welcome!

Loading comments...

Was this article helpful?
Previous ArticleOOP — Object-Oriented ProgrammingNext Article File Handling & Exceptions

📚 More Articles Like This

Sets — Complete Deep Dive

Read Article

Tuples — Complete Deep Dive

Read Article

Lists — Complete Deep Dive

Read Article