Python Tutorial chapters (19)
  1. 01Python Introduction
  2. 02Python Syntax, Keywords & Operators
  3. 03Python Variables & Data Types
  4. 04Python Strings
  5. 05Python Control Statements
  6. 06Python Lists
  7. 07Python Tuples
  8. 08Python Sets
  9. 09Python Dictionaries
  10. 10Python Functions
  11. 11Python Modules
  12. 12Python OOPs
  13. 13Python Exception Handling
  14. 14Python File Handling
  15. 15Python Searching & Sorting
  16. 16Python Advanced Topics
  17. 17Python MySQL
  18. 18Python MongoDB & SQLite
  19. 19Python MCQ

Chapter 09

Python Dictionaries

4 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

A dictionary maps unique keys to values.

This chapter covers creating and updating dictionaries, the main dictionary methods, and clear comparisons with list, set and tuple.

Dictionaries give fast lookup by name and model real-world records like JSON.

JSON data, word counts, caches, configuration, database rows.

1

Python Dictionary

A dictionary is a mutable collection of key-value pairs written as {key: value}. Keys must be unique and hashable; values can be anything. Since Python 3.7, a dictionary remembers insertion order.

In short: Like a real dictionary or phone book: you look up a word (key) to get its meaning (value).

Dictionary = key → value map

Think about it

Real data comes in labelled form, and dictionaries make that labelled access fast and readable. A student record: {"name": "Ann", "roll": 7, "marks": [80, 90]}.

Create with `{...

}, dict(name="Ann", age=20), dict([("a", 1)]) or dict.

fromkeys(keys, default)`.

Access with d[key] (KeyError if missing) or `d.

get(key, default)` (never raises).

Assigning to a new key adds it; assigning to an existing key replaces the value.

Remove with del d[key] or pop.

Membership with in checks KEYS.

Looping: for k in d, `for v in d.

values(), for k, v in d.

items()`.

Do not add or remove keys while looping over a dictionary because it raises RuntimeError; iterate over list(d) instead.

Dictionary comprehension: {x: x*x for x in range(4)}.

Nested dictionaries model JSON: d["user"]["name"].

Lookup, insert and delete are O(1) on average because of hashing.

Key points

Example

Code
Creating and using dictionaries:
student = {"name": "Ann", "age": 20, "city": "Pune"}
print(student["name"])               # Ann
print(student.get("phone"))          # None
print(student.get("phone", "N/A"))   # N/A

student["age"] = 21                  # update
student["grade"] = "A"               # add new key
del student["city"]                  # delete
print(student)   # {'name': 'Ann', 'age': 21, 'grade': 'A'}

print("name" in student, "Ann" in student)   # True False  (keys only)

for k in student:
    print(k, student[k])
for k, v in student.items():
    print(k, "->", v)

squares = {x: x * x for x in range(4)}
print(squares)                       # {0: 0, 1: 1, 2: 4, 3: 9}

print(dict(a=1, b=2))                # {'a': 1, 'b': 2}

users = {"u1": {"name": "Li", "tags": ["a", "b"]}}
print(users["u1"]["tags"][0])        # a

for k in list(student):              # safe way to delete while looping
    if k == "age":
        del student[k]
2

Python Dictionary Methods

Dictionary methods read, update and remove items. The main ones are keys, values, items, get, setdefault, update, pop, popitem, clear, copy and fromkeys.

In short: They are ready-made tools to see all keys or values, read safely, merge dictionaries and delete entries.

Think about it

Counting, grouping and merging with these methods is the most common dictionary work in exams and jobs. Counting how many times each word appears in a paragraph.

keys(), values() and items() return live VIEW objects that reflect later changes; wrap them in list() for a snapshot.

get(k, default) reads safely.

setdefault(k, default) returns the value if k exists, otherwise inserts k with default and returns it (great for grouping).

update(other) merges another dictionary or key-value pairs, overwriting duplicate keys.

pop(k, default) removes and returns a value (KeyError if no default); popitem() removes the LAST inserted pair (3.7+); clear() empties; copy() is shallow.

`dict.

fromkeys(keys, value)` shares the same value object, so avoid a mutable default like a list.

Python 3.9 adds d1 | d2 for a merged copy and d1 |= d2 to merge in place.

Sorting: `sorted(d.

items(), key=lambda kv: kv[1])` sorts by value.

Key points

  • View object: Dynamic window on keys, values or items.
  • setdefault: Get a key, or insert a default if missing.
  • popitem: Remove and return the last inserted pair.

Example

Code
Dictionary methods in use:
d = {"a": 1, "b": 2}
print(list(d.keys()))      # ['a', 'b']
print(list(d.values()))    # [1, 2]
print(list(d.items()))     # [('a', 1), ('b', 2)]

print(d.get("z", 0))       # 0
print(d.setdefault("c", 3))   # 3  (inserted)
print(d)                   # {'a': 1, 'b': 2, 'c': 3}

d.update({"b": 20, "d": 4})
print(d)                   # {'a': 1, 'b': 20, 'c': 3, 'd': 4}

print(d.pop("a"))          # 1
print(d.pop("zzz", None))  # None (no KeyError)
print(d.popitem())         # ('d', 4)  last inserted
print(d)                   # {'b': 20, 'c': 3}

print(dict.fromkeys(["x", "y"], 0))   # {'x': 0, 'y': 0}

merged = {"a": 1} | {"b": 2}          # Python 3.9+
print(merged)                         # {'a': 1, 'b': 2}

# count letters
counts = {}
for ch in "banana":
    counts[ch] = counts.get(ch, 0) + 1
print(counts)              # {'b': 1, 'a': 3, 'n': 2}

# group words by length
groups = {}
for w in ["hi", "yo", "cat"]:
    groups.setdefault(len(w), []).append(w)
print(groups)              # {2: ['hi', 'yo'], 3: ['cat']}

marks = {"ann": 70, "raj": 90, "li": 80}
print(sorted(marks.items(), key=lambda kv: kv[1], reverse=True))
# [('raj', 90), ('li', 80), ('ann', 70)]

d.clear()
print(d)                   # {}

keys / values / items

Return views for looping and converting.

get / setdefault

Safe reading and insert-if-missing.

update / | merge

Combine dictionaries; later values win.

pop / popitem / clear / del

Remove one key, the last pair, or everything.

3

Difference between List and Dictionary in Python

A list stores items accessed by numeric position (index), while a dictionary stores key-value pairs accessed by key. Lists use [], dictionaries use {key: value}.

In short: List = lockers numbered 0, 1, 2. Dictionary = lockers with names on them.

Compare two ideas side by side

Think about it

Choosing the correct structure decides if code is simple and fast. List: queue of tokens in a bank. Dictionary: account number to balance.

Access: lst[2] versus d["name"].

Order: both keep insertion order in modern Python, but a list is positional and a dictionary is by key.

Duplicates: a list allows duplicate items; a dictionary has unique keys.

Lookup speed: searching a list with in is O(n); searching a dictionary key is O(1) on average.

Memory: a dictionary uses more memory because of hashing.

Slicing and sort() exist for lists but not for dictionaries.

Keys must be hashable; list items can be anything.

Use a list for an ordered sequence of similar things, and a dictionary when you need to find data by a label.

Key points

  • Positional access: Finding an item by its index.
  • Key-based access: Finding a value by its key.

Example

Code
List vs dictionary:
lst = ["Ann", "Raj", "Li"]
d = {101: "Ann", 102: "Raj", 103: "Li"}

print(lst[1])               # Raj      (by index)
print(d[102])               # Raj      (by key)

lst.append("Sam")           # add at end
d[104] = "Sam"              # add by key

print(["a", "a"])           # duplicates allowed in list
print({"a": 1, "a": 2})     # {'a': 2}  duplicate key overwritten

print(lst[1:3])             # slicing works on list
# d[1:3]                    # TypeError: unhashable type: 'slice'

print("Li" in lst)          # searches every item (slow for big lists)
print(103 in d)             # hashed key lookup (fast)
4

Difference between List, Set, Tuple, and Dictionary in Python

List [] is ordered and mutable, tuple () is ordered and immutable, set {} is unordered with unique items, and dictionary {k: v} stores key-value pairs with unique keys.

In short: List = editable row. Tuple = locked row. Set = bag of unique items. Dictionary = labelled boxes.

Think about it

This four-way table is a frequent interview question and helps you pick the right container. Cart items (list), GPS point (tuple), unique visitors (set), user profile (dictionary).

Ordered: list, tuple and dictionary (3.7+) keep order; set does not.

Mutable: list, set, dictionary yes; tuple no.

Duplicates: list and tuple allow them; set does not; dictionary keys must be unique.

Indexing: list and tuple by number; dictionary by key; set none.

Empty creation: [], (), set(), {}.

Hashable: tuple (of hashables) can be a dict key or set item; list, set and dict cannot.

Typical use

list for changing sequences, tuple for fixed records, set for uniqueness and membership, dictionary for labelled lookup.

Convert between them with list(), tuple(), set() and dict().

Key points

Example

Code
The four collections together:
data = [1, 2, 2, 3]
print(data)                 # list  : [1, 2, 2, 3]
print(tuple(data))          # tuple : (1, 2, 2, 3)
print(set(data))            # set   : {1, 2, 3}
print(dict(zip("abc", data)))   # dict  : {'a': 1, 'b': 2, 'c': 2}

print(type([]), type(()), type(set()), type({}))

# Quick feature check
#             list  tuple  set    dict
# ordered     yes   yes    no     yes (3.7+)
# mutable     yes   no     yes    yes
# duplicates  yes   yes    no     keys unique
# index       yes   yes    no     by key
# literal     []    ()     {1,2}  {k: v}

for coll in ([1, 2], (1, 2), {1, 2}, {1: "a", 2: "b"}):
    print(type(coll).__name__, len(coll))

Solved examples

Example 01 · Basic

Count characters in "hello" using a dictionary.

Given Data:
    Required To Find:

    Character-count dictionary

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: Start with an empty dict
    Step 2: For each char use counts[ch] = counts.get(ch, 0) + 1
    Final Answer: {'h': 1, 'e': 1, 'l': 2, 'o': 1}

    Approach note: collections.Counter does the same in one line.

    Example 02 · Intermediate

    Given marks = {"ann": 70, "raj": 90, "li": 80}, find the name with the highest marks.

    Given Data:
      Required To Find:

      A name

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: max(marks, key=marks.get) compares keys by their value
      Final Answer: max(marks, key=marks.get) → "raj"

      Approach note: Use marks.items() with a lambda for more complex sorting.

      Example 03 · Basic

      What is the output of {"a": 1, "b": 2, "a": 3}?

      Given Data:
        Required To Find:

        Resulting dictionary

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: Key a is repeated
        Step 2: The last value replaces the earlier one
        Final Answer: {'a': 3, 'b': 2}

        Approach note: Position of a stays where it first appeared.

        Example 04 · Intermediate

        scores = {"ann": 80, "bob": 95, "li": 70}. Print the name with the highest score.

        Given Data:
          Required To Find:

          Name of top scorer

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: Use max on the dict with key=scores.get
          Step 2: max compares values and returns the matching key
          Step 3: bob has 95
          Final Answer: print(max(scores, key=scores.get)) # bob

          Approach note: max(dict, key=dict.get) returns the key of the largest value.

          Real-world applications

          Python

          Using Python Dictionaries in real projects

          JSON data, word counts, caches, configuration, database rows.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: "x" in d checks the values.

          Why this is wrong: Membership tests keys.

          ✅ Verified Truth: Use x in d.values() for values.

          ⚠️ Exam Tip: Frequent trick question.

          ❌ Myth: Dictionaries are unordered in Python 3.

          Why this is wrong: Since 3.7 they keep insertion order.

          ✅ Verified Truth: Sets are still unordered.

          ⚠️ Exam Tip: State the version in interviews.

          ❌ Myth: A list can be a dictionary key.

          Why this is wrong: Lists are unhashable.

          ✅ Verified Truth: Use a tuple as the key.

          ⚠️ Exam Tip: Keys must be immutable.

          Revision notes

          A dictionary maps unique keys to values. This chapter covers creating and updating dictionaries, the main dictionary methods, and clear comparisons with list, set and tuple.

          High-Yield Quick Revision Points

          1. Dict: key to value, unique hashable keys, ordered (3.7+)
          2. d[k] raises KeyError; d.get(k, default) does not
          3. in checks keys
          4. update, pop, popitem, setdefault, items
          5. List by index, dict by key
          6. List [] / tuple () / set {} unique / dict {k: v}

          Practice questions

          Question 1 · MCQ (Interview / semester)

          What does d.get("z") return if "z" is missing?

          Question 2 · MCQ (Interview / semester)

          "b" in {"a": 1, "b": 2} checks:

          Question 3 · MCQ (Interview / semester)

          Which gives the last inserted pair?

          Question 4 · MCQ (Interview / semester)

          Which collection is ordered AND immutable?

          Question 5 · MCQ (Interview / semester)

          Result of {"a": 1}.update({"a": 5})?

          Question 6 · MCQ (Interview / semester)

          Which structure is best for fast lookup by name?