MCS-201 · Unit 10

Data Structures and Control Statements in Python

Section 7 of 12

Block 3 · Unit 10Data Structures and Control Statements in Python11 min · Section 7 of 12

10.7Dictionaries

Covers IGNOU MCS-201 §10.7.6, 10.8.3

A dictionary maps keys to values, like a phone’s contact list maps names to numbers. It is the right structure whenever you need to look something up by a name or ID rather than by position, and it does so very quickly.

What a dictionary is

  • Keys must be unique and hashable: strings, numbers, tuples of immutable items, frozensets. Lists, sets and dictionaries cannot be keys.
  • Values can be anything, including lists and other dictionaries.
  • Items are accessed by key, never by position: d[0] looks for the key 0.
  • Since Python 3.7, dictionaries remember the order in which keys were inserted.

Basic operations

OperationExampleEffect
Created = {'one': 'uno', 'two': 'dos'} or dict()
Look upd['two']'dos'; KeyError if missing
Safe look-upd.get('four', 'not found')Default instead of an error
Add or changed['three'] = 'tres'Adds the key, or replaces its value
Deletedel d['one'] or d.pop('one')KeyError if missing (unless pop has a default)
Test a key'one' in dChecks keys only, not values
Sizelen(d)Number of key–value pairs

Methods

MethodPurpose
keys(), values(), items()Views of the keys, the values, and (key, value) pairs
get(key, default)Value or default; never raises KeyError
update(other)Add or overwrite pairs from another dictionary
pop(key[, default])Remove a key and return its value
popitem()Remove and return the last inserted pair
setdefault(key, default)Return the value; if the key is missing, insert it with default first
fromkeys(keys, value)New dictionary with the given keys, all set to value
copy(), clear()Shallow copy; remove everything

Looping over a dictionary gives its keys: for k in d:; use for k, v in d.items(): to get both. sorted(d) returns a sorted list of keys. dict() builds a dictionary from pairs, for example dict([('jln', 1947), ('lbs', 1964)]).

Key takeaways

  • Dictionaries map unique hashable keys to any values, with average constant-time look-up.
  • They are mutable and keep insertion order; they cannot be indexed by position or sliced.
  • get, update, pop, items, keys and values are the core methods.
  • Iterating a dictionary yields its keys.

Practice questions

Answer on paper first, then check. The explanation matters more than the letter you chose.

Question 1 · multiple choice

What does {"a": 1, "b": 2}.get("c", 0) return?

Show answer

Answer: C. 0

get returns the default given (0) when the key is missing, instead of raising KeyError.

Question 2 · multiple choice

Which cannot be a dictionary key?

Show answer

Answer: D. ["MCA"]

Lists are mutable and unhashable. Numbers, strings and tuples of immutable items are hashable.

Question 3 · multiple choice

What does this program print?

Python · quiz_dict.py
marks = {"Phy": 94, "Che": 70}
marks.update({"Che": 72, "Bio": 80})
marks["Phy"] += 1
print(marks, len(marks))
Show answer

Answer: B. {‘Phy’: 95, ‘Che’: 72, ‘Bio’: 80} 3

update replaces Che’s value and adds Bio; += 1 raises Phy to 95. Keys are unique, so there are 3 entries.

Question 4 · multiple choice

What does for x in {"a": 1, "b": 2}: give x?

Show answer

Answer: A. The keys "a" and "b"

Iterating a dictionary yields its keys; use .values() or .items() for the others.

Question 5 · multiple choice

What does this program print?

Python · quiz_wordcount.py
words = "to be or not to be".split()
freq = {}
for w in words:
    freq[w] = freq.get(w, 0) + 1
print(freq["to"], freq["be"], len(freq))
Show answer

Answer: C. 2 2 4

get(w, 0) supplies 0 for new words, so no error occurs; “to” and “be” appear twice, and there are 4 distinct words.

Question 6 · short answer

Write a dictionary that stores three students’ roll numbers (keys) and names (values), then show how to add a student, change a name, delete a student and print all entries.

Show worked answer

students = {101: "Geeta", 102: "Leena", 103: "Mahesh"}. Add: students[104] = "Amit". Change: students[103] = "Sham". Delete: del students[102] (or students.pop(102)). Print: for roll, name in students.items(): print(roll, name), which prints 101 Geeta, 103 Sham and 104 Amit in insertion order.

↑ ↓ move↵ openTab switch type