Skip to content
Computer ScienceCBSE Class 12 · Revision of Python Topics from Class XI

Dictionary Methods and Operations in Python (Class 12 Computer Science)

Updated 16 October 2026 · Fact-checked

A Python dictionary stores key: value pairs in curly brackets. Keys must be unique and immutable, and you reach a value with d[key] or d.get(key). It is mutable: assignment adds or changes a pair, update() merges another dictionary, pop() and del remove pairs, and the in operator checks keys, not values.

The in operator looks only at keys, so 'pen' in d is True but 12 in d is False; d.get() avoids the KeyError.

Illustration drawn for QuestionBuddy.

Understand Dictionary Methods and Operations

A dictionary maps keys to values: price = {'pen': 12, 'pencil': 6}. Each key appears only once; if a key is repeated when the dictionary is written, the later value wins. Keys must be immutable (numbers, strings, tuples); a list as a key raises TypeError: unhashable type: 'list'. Values can be anything, including lists and other dictionaries. Since Python 3.7 a dictionary keeps its pairs in the order they were inserted, so printed output follows that order.

Reading values. d[k] returns the value for k but raises KeyError if k is missing. d.get(k) returns None instead, and d.get(k, 0) returns the default you give. The in operator tests keys only: with the dictionary above, 'pen' in price is True but 12 in price is False (the 2026-27 sample paper asks exactly this).

Changing a dictionary. It is mutable. d[k] = v adds a new pair or replaces the value of an existing key. d.update(other) copies every pair of other into d, overwriting values of common keys. del d[k] removes a pair; d.pop(k) removes it and returns the value; d.popitem() removes and returns the last inserted pair as a tuple; d.clear() empties the dictionary. d.setdefault(k, v) returns the value of k if it exists, otherwise inserts k with v and returns v.

Building and viewing. dict() builds a dictionary, for example dict([('a', 1), ('b', 2)]). dict.fromkeys(['a', 'b'], 0) makes {'a': 0, 'b': 0} (the value defaults to None). keys(), values() and items() return views that print as dict_keys([...]), dict_values([...]) and dict_items([...]); convert with list() if a list is needed. len(d) counts pairs; max(d), min(d) and sorted(d) work on the keys; sorted(d.values()) sorts the values. d.copy() makes a new dictionary, but the values are shared, so a list stored as a value is still the same list in both.

Traversal. for k in d: visits keys; for k, v in d.items(): gives both. Changing values while looping is fine, but adding or deleting keys inside the loop raises RuntimeError.

Dictionaries appear in every recent sample paper: as 1-mark output items, as the data for the stack question, and in 2-3 mark functions such as counting the frequency of words or characters, where d[x] = d.get(x, 0) + 1 is the key line.

Dictionary Methods and Operations: key facts

Reading and testing
d[k]value of k; KeyError if k is missing
d.get(k)value, or None if missing
d.get(k, v)value, or v if missing
k in dTrue if k is a key (values are not checked)
len(d)number of pairs
To test a value, use v in d.values().
Adding, changing and removing
d[k] = vadds k, or replaces its value
d.update(e)copies all pairs of e; common keys take e's values
del d[k]removes the pair; KeyError if missing
d.pop(k)removes the pair and returns its value
d.popitem()removes and returns the last inserted pair as a tuple
d.clear()empties d
Only pop() and popitem() give back what they removed.
Creating dictionaries
dict(pairs)from a sequence of (key, value) pairs
dict.fromkeys(seq, v)every key in seq gets v (None if v is omitted)
d.setdefault(k, v)returns d[k] if present, else adds k: v and returns v
d.copy()a new dictionary with the same pairs
copy() is shallow: a list value is shared by both dictionaries.
Views and functions on keys
d.keys()dict_keys view of the keys
d.values()dict_values view
d.items()dict_items view of (key, value) tuples
max(d), min(d), sorted(d)work on keys
sorted(d.values())a sorted list of the values
Wrap a view in list() before indexing it.
Frequency-count pattern
  1. 1.freq = {}
  2. 2.for x in data:
  3. 3.freq[x] = freq.get(x, 0) + 1
The standard answer to 'count the occurrences of each word or character'.

How to answer Dictionary Methods and Operations questions

Follow these steps for dictionary output questions and dictionary functions.

  1. 1Write the dictionary as a table of keys and values in insertion order.
  2. 2For each statement, decide whether it adds a key (new key), changes a value (existing key) or removes a pair; new keys go to the end of the order.
  3. 3Note what each call returns: pop() gives the value, popitem() gives a (key, value) tuple, setdefault() gives the existing or new value, update() and clear() give None.
  4. 4Remember that in, max(), min() and sorted() look at keys unless you pass d.values().
  5. 5For a missing key, d[k] raises KeyError but d.get(k) gives None; check which one the code uses.
  6. 6In programs, traverse with for k in d: or for k, v in d.items(): and build results in a separate list or dictionary.
  7. 7Write printed dictionaries exactly: {'a': 1, 'b': 2}, with a colon and a space after each key.

Dictionary Methods and Operations in real life

The idea, met in an everyday situation. Answer the question in your own words, then compare with the model answer. The one-line hook is what to remember.

Counting with get()

Suppose a class votes for a class representative and the votes are collected in a list: votes = ['Riya', 'Aman', 'Riya', 'Zoya', 'Riya', 'Aman'].

Count the votes for each candidate with a dictionary and print the winner.

Try it first, then show the solutionSolution
  1. Start with an empty dictionary and add 1 to each candidate's count; get(name, 0) supplies 0 the first time a name appears.
  2. votes = ['Riya', 'Aman', 'Riya', 'Zoya', 'Riya', 'Aman']
    tally = {}
    for v in votes:
        tally[v] = tally.get(v, 0) + 1
    print(tally)
    best = ''
    for name in tally:
        if best == '' or tally[name] > tally[best]:
            best = name
    print('Winner:', best)
  3. Riya has 3 votes, Aman 2 and Zoya 1.

Answer: {'Riya': 3, 'Aman': 2, 'Zoya': 1}
Winner: Riya

Memory hook: get(name, 0) is the ballot box that starts empty for every new candidate.

update() merges and overwrites

Imagine your phone stores contacts as contacts = {'Mom': '98110', 'Ravi': '99220'} and you import a list from a new SIM: new = {'Ravi': '90000', 'Asha': '97770'}.

After contacts.update(new), what is Ravi's number and how many contacts are there? Then delete Mom's entry with pop() and show what pop() returns.

Try it first, then show the solutionSolution
  1. update() copies every pair of new: Ravi is a common key, so his number is overwritten; Asha is added at the end.
  2. contacts = {'Mom': '98110', 'Ravi': '99220'}
    new = {'Ravi': '90000', 'Asha': '97770'}
    contacts.update(new)
    print(contacts['Ravi'], len(contacts))
    print(contacts.pop('Mom'), contacts)

Answer: 90000 3
98110 {'Ravi': '90000', 'Asha': '97770'}

Memory hook: update() is a SIM import: new names are added, old names get the new number.

Tricks to remember Dictionary Methods and Operations

Short memory aids. Say each one aloud once, then use it on a question the same day.

  • Keys are locks, so they must not change

    A key is like a locker number: it must stay fixed, so only immutable types (int, str, tuple) can be keys.

    Use it when: Why a list cannot be a key.

  • in looks at the labels

    in, max, min and sorted read the labels (keys), never the contents (values), unless you hand them d.values().

    Use it when: MCQs such as 12 in d.

  • Square brackets shout, get() whispers

    d[k] shouts KeyError when k is missing; d.get(k) quietly returns None (or your default).

    Use it when: Choosing between d[k] and get().

  • popitem() is a stack pop

    popitem() takes the most recently added pair, like popping the top of a stack.

    Use it when: Output questions on popitem().

Dictionary Methods and Operations: solved examples

Ordered from board level to HOTS. Try each one before you open the solution.

Example 1: Membership and get() · 1 mark · Very short answerBoard level

Write the output:

d = {'Pen': 12, 'Ink': 6}
print('Pen' in d, 12 in d, d.get('Ruler'))
Try it first, then show the solutionSolution
  1. 'Pen' is a key: True. 12 is a value, and in checks keys only: False.
  2. 'Ruler' is missing; get() returns None instead of raising KeyError.

Answer: True False None

Example 2: update(), pop() and setdefault() · 2 marks · Short answerHarder board level

Predict the output:

stock = {'pen': 10, 'pad': 4}
stock.update({'pad': 7, 'ink': 3})
x = stock.pop('pen')
y = stock.setdefault('ink', 50)
z = stock.setdefault('tape', 2)
print(stock, x, y, z)
Try it first, then show the solutionSolution
  1. update: 'pad' becomes 7 and 'ink': 3 is added → {'pen': 10, 'pad': 7, 'ink': 3}.
  2. pop('pen') removes the pair and returns 10. (½ mark)
  3. setdefault('ink', 50): 'ink' exists, so its value 3 is returned and nothing changes. (½ mark)
  4. setdefault('tape', 2): 'tape' is new, so it is added with 2 and 2 is returned. (1 mark for the final dictionary)

Answer: {'pad': 7, 'ink': 3, 'tape': 2} 10 3 2

Example 3: Character frequency · 3 marks · Short answerHarder board level

Write a function count_chars(s) that returns a dictionary of how many times each character (other than a space) occurs in s. Show the result for 'banana bread'.

Try it first, then show the solutionSolution
  1. Loop over the string, skip spaces, and add 1 using get() with default 0. (2 marks)
  2. def count_chars(s):
        freq = {}
        for ch in s:
            if ch != ' ':
                freq[ch] = freq.get(ch, 0) + 1
        return freq
    print(count_chars('banana bread'))
  3. Return the dictionary (1 mark). Keys appear in the order each character is first met: b, a, n, r, e, d.

Answer: {'b': 2, 'a': 4, 'n': 2, 'r': 1, 'e': 1, 'd': 1}

Example 4: Traversing with items() · 2 marks · Short answerHarder board level

R = {'Asha': 82, 'Dev': 67, 'Kiran': 91, 'Mona': 74}. Write code to display the names of students who scored above 75 and the class average, using items().

Try it first, then show the solutionSolution
  1. R = {'Asha': 82, 'Dev': 67, 'Kiran': 91, 'Mona': 74}
    for name, m in R.items():
        if m > 75:
            print(name)
    print('Average:', sum(R.values()) / len(R))
  2. Loop with the condition (1 mark); sum of values divided by the number of pairs (1 mark): 314 / 4 = 78.5.

Answer: Asha
Kiran
Average: 78.5

Example 5: fromkeys(), popitem() and functions on keys · 2 marks · Short answerHOTS / competency

Predict the output:

d = dict.fromkeys(['a', 'b', 'c'], 0)
d['b'] += 5
k = d.popitem()
print(d, k, max(d), sorted(d.values()))
Try it first, then show the solutionSolution
  1. fromkeys gives {'a': 0, 'b': 0, 'c': 0}; then 'b' becomes 5.
  2. popitem() removes the last inserted pair and returns it as a tuple: ('c', 0). (1 mark)
  3. max(d) compares keys: 'b' > 'a'. sorted(d.values()) sorts the values: [0, 5]. (1 mark)

Answer: {'a': 0, 'b': 5} ('c', 0) b [0, 5]

Example 6: Case study: a canteen price list · 4 marks · Case-basedHOTS / competency

Suppose a school canteen keeps menu = {'samosa': 15, 'juice': 30, 'sandwich': 40}.
(i) Write a loop that raises every price by 10%. (1 mark)
(ii) A customer asks for 'pizza'. Write one statement that prints its price or 'Not available' without an error. (1 mark)
(iii) The manager tries menu[['tea', 'coffee']] = 20 to add two drinks at one price. What happens, and what is a correct way? (2 marks)

Try it first, then show the solutionSolution
  1. (i) Changing values (not keys) inside a loop is allowed:
    menu = {'samosa': 15, 'juice': 30, 'sandwich': 40}
    for item in menu:
        menu[item] = menu[item] * 1.1
    print(menu)
    print(menu.get('pizza', 'Not available'))
  2. (ii) get() with a default avoids KeyError: print(menu.get('pizza', 'Not available')).
  3. (iii) A list is mutable, so it cannot be a key: Python raises TypeError: unhashable type: 'list'. Add each drink separately, e.g. menu.update(dict.fromkeys(['tea', 'coffee'], 20)).

Answer: (i) {'samosa': 16.5, 'juice': 33.0, 'sandwich': 44.0} (ii) Not available (iii) TypeError: unhashable type: 'list'; use menu.update(dict.fromkeys(['tea', 'coffee'], 20)).

Where students lose marks in Dictionary Methods and Operations

The slips examiners see most often, and what to write instead.

  • Mistake: Using in to look for a value

    The in operator checks only the keys of a dictionary.

    Wrong working

    d = {'Pen': 12}
    print(12 in d) # True

    Right working

    print(12 in d) # False
    print(12 in d.values()) # True

    Do this: Use d.values() when the question is about values.

    Usually costs: 1 mark in MCQs.

  • Mistake: Reading a missing key with square brackets in a counting loop

    The first time a word is met, d[w] does not exist, so d[w] + 1 raises KeyError.

    Wrong working

    for w in words:
    d[w] = d[w] + 1

    Right working

    for w in words:
    d[w] = d.get(w, 0) + 1

    Do this: Use get() with default 0, or test if w in d first.

    Usually costs: 1 mark in a 3-mark program.

  • Mistake: Thinking max(d) gives the largest value

    max, min and sorted on a dictionary work on its keys.

    Wrong working

    max({'a': 9, 'b': 2}) → 9

    Right working

    max({'a': 9, 'b': 2}) → 'b'; max(d.values()) → 9

    Do this: Pass d.values() when values are wanted.

    Usually costs: 1 mark.

  • Mistake: Writing the output of keys() as a plain list

    keys(), values() and items() return view objects that print with their type name.

    Wrong working

    print({'a': 1}.keys()) → ['a']

    Right working

    print({'a': 1}.keys()) → dict_keys(['a'])

    Do this: Copy the view's name into the answer, or use list(d.keys()) in code.

    Usually costs: Half to 1 mark.

Exam tips

  • Learn the frequency pattern d[x] = d.get(x, 0) + 1; it answers most 'count each word/character' questions in two lines.
  • Stack questions in Section C often hand you the data as a dictionary: loop with for k in d: and push the key or d[k] as the question asks.
  • In output questions, keep the insertion order: new keys go to the end, and changing a value does not move its key.
  • If a question says 'without raising an error', it is pointing you to get() or to an in check.
  • When printing a dictionary, write it exactly: {'a': 1, 'b': 2}, with quotes around string keys and a space after each colon and comma.

Practice questions on Dictionary Methods and Operations

Write each answer on paper first. Open the hint only if you are stuck, and the answer only when you have finished.

  1. Q1 · 1 mark · MCQBoard level

    Which dictionary method returns the value of a key, or a default value if the key is not present, without raising an error?
    (a) pop() (b) get() (c) keys() (d) items()

    Hint

    It whispers instead of shouting.

    Answer

    (b) get()

  2. Q2 · 1 mark · Very short answerBoard level

    Write the output:

    d = {1: 'a', 2: 'b'}
    d[3] = 'c'
    d[1] = 'z'
    print(d, len(d))
    Hint

    One new key and one changed value.

    Answer

    {1: 'z', 2: 'b', 3: 'c'} 3

  3. Q3 · 1 mark · MCQBoard level

    What happens when the following code runs?

    d = {'a': 1}
    print(d['b'])

    (a) prints None (b) prints 0 (c) KeyError (d) IndexError

    Hint

    Square brackets on a missing key.

    Answer

    (c) KeyError

  4. Q4 · 2 marks · Short answerHarder board level

    Predict the output:

    D = {'x': 3, 'y': 1, 'z': 2}
    T = 0
    for k, v in D.items():
        if v > 1:
            T += v
            D[k] = v * 10
    print(D, T)
    Hint

    Only the values 3 and 2 pass the test.

    Answer

    {'x': 30, 'y': 1, 'z': 20} 5

  5. Q5 · 3 marks · Short answerHarder board level

    A dictionary E stores employee names and salaries. Write a function high_salary(E, limit) that returns a list of names whose salary is more than limit. Show the result for E = {'Anil': 52000, 'Bina': 47000, 'Charu': 61000} and limit 50000.

    Hint

    Loop over items() and append the key.

    Answer
    def high_salary(E, limit):
        names = []
        for n, s in E.items():
            if s > limit:
                names.append(n)
        return names
    print(high_salary({'Anil': 52000, 'Bina': 47000, 'Charu': 61000}, 50000))

    Output: ['Anil', 'Charu']

  6. Q6 · 1 mark · Assertion-reasonHarder board level

    Assertion (A): A list cannot be used as a key in a Python dictionary.
    Reason (R): Dictionary keys must be of an immutable type.
    (a) Both A and R are true and R is the correct explanation of A. (b) Both A and R are true but R is not the correct explanation of A. (c) A is true but R is false. (d) A is false but R is true.

    Hint

    What error does a list key raise?

    Answer

    (a) Both are true and R explains A: a list is mutable, so it raises TypeError: unhashable type: 'list'.

  7. Q7 · 2 marks · Short answerHOTS / competency

    Predict the output and explain why a changed:

    a = {'k': [1, 2], 'n': 5}
    b = a
    c = a.copy()
    b['n'] = 6
    c['k'].append(3)
    c['n'] = 7
    print(a)
    Hint

    b is an alias; c is a new dictionary whose values are shared.

    Answer

    {'k': [1, 2, 3], 'n': 6}. b is the same dictionary as a, so b['n'] = 6 changes a. c is a separate dictionary, so c['n'] = 7 does not, but c['k'] is the same list object as a['k'], so appending 3 shows in a.

Test your recall

Answer in your head or on paper first, then open the card. Pulling an answer out of memory makes it stick far better than re-reading.

  1. 1.What does d.get('x', 0) return if 'x' is not a key?Show answer

    0.

  2. 2.Which method removes and returns the last inserted pair?Show answer

    popitem(), as a (key, value) tuple.

  3. 3.What does dict.fromkeys(['p', 'q']) give?Show answer

    {'p': None, 'q': None}.

  4. 4.Can a tuple be a dictionary key?Show answer

    Yes (if its items are immutable too), because a tuple is immutable.

  5. 5.What does setdefault() return when the key already exists?Show answer

    The existing value; the dictionary is not changed.

  6. 6.What does sorted({'b': 1, 'a': 2}) return?Show answer

    ['a', 'b'], the sorted keys.

Dictionary Methods and Operations: frequently asked questions

What is the difference between d[key] and d.get(key)?

Both return the value for an existing key. For a missing key, d[key] raises KeyError while d.get(key) returns None, or the default given as the second argument, such as d.get(key, 0).

Which dictionary methods are in the CBSE Computer Science syllabus?

len(), dict(), keys(), values(), items(), get(), update(), del, clear(), fromkeys(), copy(), pop(), popitem(), setdefault(), max(), min() and sorted(), along with accessing, adding, modifying and traversing items.

Does a Python dictionary keep its order?

Yes. From Python 3.7, a dictionary remembers insertion order, so loops and print() show pairs in the order they were added. Changing a value keeps the key in its place.

Why can't a list be a dictionary key?

Keys must be immutable so that they can be found reliably. A list can change, so Python raises TypeError: unhashable type: 'list'. Use a tuple instead if you need a key with several parts.

How do I count the frequency of words in a string using a dictionary?

Split the string into words and, for each word w, write d[w] = d.get(w, 0) + 1. At the end, d maps each word to the number of times it occurs.