Dictionaries and Sets

Computer Science – XI · Chapter 11 · Questions and Answers

11.1–11.2 Creating and accessing dictionaries

1. What is a dictionary? Why is it so called?

A dictionary stores data as key–value pairs. Each key acts as a meaningful label instead of a numeric index. It works like a real dictionary, where a word (key) helps find its meaning (value), or an address book where a name is the key and the details are the value. Dictionaries are also called associative arrays or hashes.

2. What is key–value mapping? What rules apply to keys?
  • Each key points to exactly one value; keys must be unique.
  • Keys must be hashable, so only immutable objects (integers, strings, tuples containing only immutable elements) can be keys. Lists cannot be keys.
  • Values can be of any type, including lists and other dictionaries.
  • Dictionaries preserve the order in which pairs are added but are accessed by key, not by numeric index.
3. What does "hashable" mean? Why can't a list be a key?

An object is hashable if it has a fixed hash value that remains the same throughout its lifetime. Hashing computes a unique integer from the object's contents, and Python uses it to quickly locate the dictionary entry. A list is mutable, so its contents (and hash) could change, and it cannot maintain a stable hash value.

4. How is a dictionary created? Give examples with the students and capitals dictionaries.

Enclose key–value pairs in curly braces; a colon separates key and value and commas separate pairs:

students = {101: "Abhilash", 102: "Ayra", 103: "Azim", 104: "Brijesh", 105: "Jaya"}
capitals = {"India": "New Delhi", "Oman": "Muscat", "Japan": "Tokyo"}

Keys in the first are admission numbers (integers); in the second, keys and values are both strings.

5. How can a dictionary be created using dict()? How is an empty dictionary created?
software_freedom = dict(
    F0="The freedom to run the program for any purpose.",
    F1="The freedom to study how the program works and modify it.")
empty_dict = {}

With dict(), keys are written as names (keyword arguments) without quotes. An empty dictionary prints as {} and is useful when data is added later.

6. How are values accessed? What happens if the key is missing?

Use dictionary[key].

>>> print(students[103])
Azim
>>> print(capitals["Oman"])
Muscat
>>> capitals["Bhutan"]
KeyError: 'Bhutan'
7. Explain the get() method. How does it differ from square brackets?

get(key) returns the value for the key, but if the key is missing it does not raise an error; it returns None or a default value that we specify.

>>> print(capitals.get("Bhutan"))
None
>>> print(capitals.get("Bhutan", "Not in the list"))
Not in the list

11.3 Dictionaries with compound values

8. What are compound values? Which collections can be used as values?

When a key needs to represent more than one piece of information, its value can be a list, tuple, set or even another dictionary. Lists are suitable when data may change (mutable); tuples are preferred for fixed items that should remain constant.

9. Explain a dictionary with lists as values. How are list items updated or added?
cyber_attacks = {
    "Network": ["Phishing", "DoS", "Spoofing"],
    "Common": ["Virus", "Worm"]
}
print(cyber_attacks["Network"])               # ['Phishing', 'DoS', 'Spoofing']
cyber_attacks["Network"][2] = "IP Spoofing"   # change item at index 2
cyber_attacks["Common"].append("Spam")        # add to a list

First the key gives the list, then an index or a list method works on that list.

10. Explain a dictionary with tuples as values. Why use tuples?

Tuples protect fixed information from accidental change. In country_info, each country maps to a tuple (country code, dialling code, continent):

country_info = {"India": ("IN", "+91", "Asia"), "Nigeria": ("NG", "+234", "Africa")}
print(country_info["India"])          # ('IN', '+91', 'Asia')
print(country_info["India"][0])       # IN
print(country_info["Nigeria"][2])     # Africa
11. What is a nested dictionary? How are inner values accessed?

A dictionary that contains another dictionary as a value, useful when one item has several related details.

employee = {
    "Emp101": {"name": "Sajimon Abraham", "email": "sajim@example.com", "phone": 9876543210},
    "Emp102": {"name": "Kavitha P", "email": "kavitha@example.com", "phone": 9876501234}
}
print("Name of Emp101:", employee["Emp101"]["name"])     # Sajimon Abraham
print("Phone of Emp102:", employee["Emp102"]["phone"])   # 9876501234

Keys are case sensitive: the dictionary uses lowercase "name" and "phone", so writing ["Name"] or ["Phone"] would raise a KeyError.

12. Create a dictionary of ten favourite books with first author, publisher and year, and print it.
books = {
    "Wings of Fire": ("A. P. J. Abdul Kalam", "Universities Press", 1999),
    "Malgudi Days": ("R. K. Narayan", "Indian Thought Publications", 1943),
    "Atomic Habits": ("James Clear", "Penguin Random House", 2018),
    # ... add seven more books in the same format
}
for title in books:
    print(title, "->", books[title])

Use title as the key (strings are hashable) and a tuple for the fixed details. Replace the sample entries with your own ten books.

11.4 Updating and managing dictionary data

13. Is a dictionary mutable? What does updating mean?

Yes. Updating means any modification of existing key–value pairs or adding new ones.

14. Explain the update() method.

Merges one dictionary into another or adds several items at once. If a key exists, its value is updated; if not, a new pair is added.

d = {"a": 1, "b": 2}
d.update({"b": 20, "c": 3})
print(d)     # {'a': 1, 'b': 20, 'c': 3}
15. How is a new key–value pair added?

Assign a value to a non-existent key:

inventory = {"Apples": 60, "Bananas": 100, "Oranges": 75}
inventory["Mulberry"] = 180
print(inventory)
# {'Apples': 60, 'Bananas': 100, 'Oranges': 75, 'Mulberry': 180}
16. How is a complete value (such as a list) replaced?
student = {"name": "Aisha", "scores": [85, 90, 92]}
student["scores"] = [95, 98, 100]
print(student)     # {'name': 'Aisha', 'scores': [95, 98, 100]}
17. How is a key–value pair removed? What if the key is absent?
del inventory["Oranges"]
print(inventory)     # {'Apples': 60, 'Bananas': 100, ...}

If the key does not exist, del raises a KeyError.

11.5 Dictionary functions

18. Explain the common dictionary methods (Table 11.1).
MethodRemarks
keys()List-like view of all keys
values()List-like view of all values
items()Key–value pairs as tuples
update({key: value})Adds a new pair or updates an existing key
pop(key)Removes the key and returns its value
popitem()Removes and returns the last inserted key–value pair
19. Demonstrate these methods on a gadget inventory.
gadgets = {"Laptop": 12, "Phone": 30, "Tablet": 8}
print(gadgets.keys())       # dict_keys(['Laptop', 'Phone', 'Tablet'])
print(gadgets.values())     # dict_values([12, 30, 8])
print(gadgets.items())      # dict_items([('Laptop', 12), ('Phone', 30), ('Tablet', 8)])
gadgets.update({"Camera": 5})
print(gadgets.pop("Phone"))     # 30
print(gadgets.popitem())        # ('Camera', 5)
print(gadgets)                  # {'Laptop': 12, 'Tablet': 8}
20. How can a dictionary be traversed with a for loop?
for key in gadgets:
    print(key, gadgets[key])

for key, value in gadgets.items():
    print(key, "=", value)

Looping over the dictionary gives its keys; items() gives (key, value) tuples that can be unpacked.

11.6 Application of dictionary

21. Write the shopping cart application and explain its functions.

A dictionary ensures each item is listed once; adding the same item again updates its quantity.

def add_to_cart(cart, input_list):
    item, qty = input_list[0], input_list[1]
    if item in cart:
        cart[item] = cart[item] + qty      # item exists: increase quantity
    else:
        cart[item] = qty                   # new item

def show_cart(cart):
    print("Number of different items:", len(cart))
    print("Total quantity:", sum(cart.values()))
    print("Item        Quantity")
    for item, qty in cart.items():
        print(f"{item:<12}{qty}")

cart = {}
n = int(input("How many items do you want to add? "))
for i in range(n):
    name = input("Item name: ")
    qty = int(input("Quantity: "))
    add_to_cart(cart, [name, qty])
show_cart(cart)
  • add_to_cart(cart, input_list): receives the item name and quantity as a two-element list; updates the quantity if the item exists, otherwise adds a new key.
  • show_cart(cart): shows the number of different items, total quantity and a table of items with quantities.
  • Main program: creates the empty dictionary, loops to read inputs, calls add_to_cart(), then show_cart().

For Pen 2, Book 1, Pen 3: 2 different items, total quantity 6, Pen 5 and Book 1.

22. Write a program with a dictionary of words and synonyms using separate functions.
def create_dictionary():
    return {
        "big": ["large", "huge", "giant"], "small": ["tiny", "little"],
        "happy": ["glad", "joyful"], "fast": ["quick", "rapid"],
        "smart": ["clever", "bright"], "begin": ["start", "commence"],
        "end": ["finish", "conclude"], "angry": ["mad", "furious"],
        "brave": ["bold", "fearless"], "quiet": ["silent", "calm"]
    }

def display(syn, word):
    print("Words:", list(syn.keys()))
    print("Synonym lists:", list(syn.values()))
    print("Synonyms of", word, ":", syn[word])

def update(syn):
    syn["big"].append("massive")                 # new synonym for an existing word
    syn["cold"] = ["chilly", "freezing"]         # completely new word

synonyms = create_dictionary()
display(synonyms, "happy")
update(synonyms)
print(synonyms)
23. Write a program for countries and their rivers, mountains, deserts and seas.
def create_dictionary():
    return {
        "India": ["Ganga", "Himalayas", "Thar", "Arabian Sea"],
        "Egypt": ["Nile", "Mount Sinai", "Sahara", "Red Sea"],
        "China": ["Yangtze", "Mount Everest", "Gobi", "South China Sea"]
    }

def print_countries(d):
    for country in d.keys():
        print(country)

def print_features(d):
    for features in d.values():
        print(features)

def print_pairs(d):
    for country, features in d.items():
        print(country, "-> River:", features[0], "| Mountain:", features[1],
              "| Desert:", features[2], "| Sea:", features[3])

data = create_dictionary()
print_countries(data)
print_features(data)
print_pairs(data)
24. Keep marks of 10 students in 3 subjects with the key (student name, exam name) and a list of three marks. Allow adding and viewing.
marks = {}

def add_marks(name, exam, m_list):
    marks[(name, exam)] = m_list

def show_marks(name, exam):
    key = (name, exam)
    if key in marks:
        m = marks[key]
        print("Mathematics:", m[0], "Physics:", m[1], "Chemistry:", m[2])
    else:
        print("No record found")

while True:
    choice = input("1. Add marks  2. View marks  3. Exit: ")
    if choice == "1":
        n = input("Student name: ")
        e = input("Exam (Term 1/Term 2/Term 3): ")
        ml = [int(input("Mathematics: ")), int(input("Physics: ")), int(input("Chemistry: "))]
        add_marks(n, e, ml)
    elif choice == "2":
        show_marks(input("Student name: "), input("Exam: "))
    else:
        break

A tuple is used as the key because tuples are immutable and hashable; a list could not be a key.

11.7 Sets

25. What is a set? What are its features?

A set is an unordered collection of unique elements. Elements have no fixed position and cannot be accessed by index; duplicates are removed automatically; elements must be immutable (numbers, strings, tuples). Sets are useful for removing duplicates and for union, intersection and difference.

26. How are sets created? Why does {} not create an empty set?
numbers = {10, 20, 30, 10}
print(numbers)            # {10, 20, 30}
random_num = {7, 9, 11, 10, 4, 10, 20, 3, 6, 11}
print(random_num)         # {3, 4, 6, 7, 9, 10, 11, 20}
letters = set("balloon")
print(letters)            # each letter once; order may vary
empty_set = set()
print(empty_set)          # set()

Empty braces {} create an empty dictionary, so an empty set must be created with set(). The order of a set's elements cannot be predicted and may vary.

27. Explain the set operations and methods (Table 11.2) with a = {1,2,3}, b = {3,4,5}.
Function / operatorRemarksExample
union() or |All unique elements of both setsa|b → {1, 2, 3, 4, 5}
intersection() or &Elements common to botha&b → {3}
difference() or -Elements in a not in ba-b → {1, 2}
add()Adds one elementa.add(6) → {1, 2, 3, 6}
remove()Removes an element; error if absenta.remove(3)
discard()Removes an element; no error if absenta.discard(10)
clear()Removes all elementsa.clear() → set()
28. Apply the operations to lng1 = {"Python","C","Java"} and lng2 = {"JavaScript","Python","Go"}.

lng1.union(lng2) → {'Python', 'C', 'Java', 'JavaScript', 'Go'}
lng1.intersection(lng2) → {'Python'}
lng1.difference(lng2) → {'C', 'Java'}

The order shown on screen may differ because sets are unordered.

29. Differentiate between remove() and discard().

Both delete an element from a set. If the element is absent, remove() raises a KeyError, while discard() does nothing.

30. Compare the subjects chosen by two students using sets (Figure 11.12).
A = {"Physics", "Chemistry", "Maths", "Computer Science"}
B = {"Chemistry", "Maths", "Biology", "Economics"}
print("Common subjects:", A & B)
print("Only Student A:", A - B)
print("Only Student B:", B - A)

Common: {'Chemistry', 'Maths'}; only A: {'Physics', 'Computer Science'}; only B: {'Biology', 'Economics'}.

31. Write a program to display the unique words of a sentence using get_sentence() and show_unique_words().
def get_sentence():
    return input("Enter a sentence: ")

def show_unique_words(sentence):
    words = sentence.split()        # splits on spaces by default
    unique = set(words)
    print("Unique words:", unique)

show_unique_words(get_sentence())

For "to be or not to be", the output is a set containing 'to', 'be', 'or' and 'not' (in any order). To ignore case, use sentence.lower().split().

Practice programs and quick questions

32. Write a password validity program using functional decomposition.

Valid if the password has at least one uppercase letter, one digit and one special character from {"@", "#", "$", "&"}.

def get_password():
    return input("Enter password: ")

def has_special(pw):
    specials = {"@", "#", "$", "&"}
    return len(set(pw) & specials) > 0

def check(pw):
    upper = any(ch.isupper() for ch in pw)
    digit = any(ch.isdigit() for ch in pw)
    if upper and digit and has_special(pw):
        print("Valid password")
    else:
        print("Invalid password")

check(get_password())

Here a set intersection tests for special characters. "Python@25" is valid; "python25" is invalid.

33. Identify the unique words in one or more sentences with separate functions.
def accept_sentences():
    n = int(input("How many sentences? "))
    text = ""
    for i in range(n):
        text = text + " " + input("Sentence: ")
    return text

def to_set(text):
    return set(text.lower().split())

def display(words):
    print("Unique words:", words)

display(to_set(accept_sentences()))
34. Analyse participation of 7 students in the competitions Quiz, Web Designing, Coding and Animation using a list of tuples (name, set).
students = []
for i in range(7):
    name = input("Student name: ")
    comps = set(input("Competitions (comma separated, max 3): ").split(","))
    students.append((name, comps))

def show_participants(competition):
    found = False
    for name, comps in students:
        if competition in comps:
            print(name)
            found = True
    if not found:
        print("No participants")

show_participants(input("Enter competition name: "))

Each tuple holds the student's name and the set of competitions registered for. Sets make the membership test competition in comps simple, and set operations can find students in both of two competitions (&) or in either (|).

35. Differentiate between list, tuple, dictionary and set.
FeatureListTupleDictionarySet
Brackets[ ]( ){key: value}{ } / set()
OrderedYesYesKeeps insertion order; accessed by keyNo
MutableYesNoYesYes (elements must be immutable)
DuplicatesAllowedAllowedKeys uniqueNot allowed
AccessIndexIndexKeyNo indexing
36. Fill in the blanks / one-word answers.
  • A dictionary stores data as ______ pairs: key–value.
  • Error when accessing a missing key with square brackets: KeyError.
  • Method that returns None instead of an error for a missing key: get().
  • Method that removes the last inserted pair: popitem().
  • Function to create an empty set: set().
  • Operator for intersection: &; union: |; difference: –.
  • Type that can never be a dictionary key: a mutable type such as a list.