11. Dictionaries and Sets
Higher Secondary · Computer Science · Science Stream

Dictionaries and Sets

A dictionary stores data as key–value pairs, where each key acts like a meaningful label instead of a numeric index. A set is an unordered collection of unique items, ideal for removing duplicates and performing mathematical operations such as union, intersection, and difference. This chapter covers creating and accessing dictionaries, compound and nested values, updating and managing dictionary data, built-in dictionary and set functions, and applications such as a shopping cart and unique-word finder.

11.1 – 11.2 · Live Tool

Dictionary Key Lookup Lab

Build a dictionary as comma-separated key:value pairs, then try dictionary[key] or dictionary.get(key, default) and watch the map highlight the matching pair — or raise a KeyError if the key is missing.

Try a Lookup

● live
Enter key:value pairs, pick D[key] or get(), type a key, then press Run.
Try key Bhutan with D[key] to see a KeyError · switch to get() with the same key to see it return the default instead.
11.1

Creating Dictionary

A dictionary can be created as a collection of key–value pairs enclosed in curly braces { }. Each key is followed by a colon : and each pair is separated by a comma.

dictionary_name = {key1: value1, key2: value2, key3: value3, …} >>>students = { 101:"Abhilash", 102:"Ayra", 103:"Azim", 104:"Brijesh", 105:"Jaya" }

Here, the keys are the admission numbers (101, 102, 103, 104, 105) and the values are the names. Both keys and values can also be strings:

>>>capitals = { "India":"New Delhi", "Mongolia":"Ulaanbaatar", "France":"Paris", "Oman":"Muscat", "Japan":"Tokyo", "Brazil":"Brasília", "Mali":"Bamako" }

Keys must be hashable

A Python object must be hashable to be used as a key — it must have a fixed internal hash value throughout its lifetime. Only immutable types (integers, strings, tuples of immutable elements) are hashable.

Mutable types cannot be keys

Lists cannot be dictionary keys because they can change after creation, so they cannot maintain a stable hash value. Each key must also be unique.

Order is preserved

Although items are not accessed by numeric index, Python dictionaries preserve the order in which key–value pairs were added.

Associative arrays

Dictionaries are sometimes called associative arrays or hashes — the "index" is the key itself, which can be a string, number, or any other immutable type.

Creating with dict()

>>>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.", F2="The freedom to redistribute copies to help others.", F3="The freedom to improve the program and release your improvements." )

We can create an empty dictionary using {}, as empty_dict = {}. Printing it displays {} — empty dictionaries are useful when we want to start with no data and add items later.

11.2

Accessing Dictionary Elements

Dictionaries allow quick access to values based on their keys. The standard way to access a value is value = dictionary[key].

>>>print(students[103]) Azim >>>print(capitals["Oman"]) Muscat >>>print(capitals["Bhutan"]) Traceback (most recent call last): KeyError: 'Bhutan'

If we try to access a key that does not exist, Python raises a KeyError. The get() method works like square brackets, but instead of raising an error for a missing key, it returns None or a default value we specify.

>>>print(capitals["Mongolia"]) Ulaanbaatar >>>print(capitals.get("Bhutan")) None >>>print(capitals.get("Bhutan", "Value Not Found")) Value Not Found
11.3

Dictionaries with Compound Values

A single key may need to represent more than one piece of information. Dictionaries can use compound values, where the value associated with a key is a list, tuple, set, or even another dictionary.

11.3.1 Dictionary with Lists as Values

Lists are suitable when the data may change, because they are mutable. Individual items within these lists can be updated using indexing, and new items can be appended.

>>>cyber_attacks = { "Common": ["Malware", "Phishing"], "Advanced": ["DDoS", "Ransomware", "Prompt Injection"], "Network": ["Man-in-the-Middle", "Packet Sniffing", "Spoofing"], "Authentication": ["Brute Force", "Credential Stuffing", "Password Spraying"] } >>>print(cyber_attacks["Network"]) ['Man-in-the-Middle', 'Packet Sniffing', 'Spoofing'] # Update an item within the list >>>cyber_attacks["Network"][2] = "IP Spoofing" >>>print(cyber_attacks["Network"]) ['Man-in-the-Middle', 'Packet Sniffing', 'IP Spoofing'] # Add a new item to the list >>>cyber_attacks["Common"].append("Spam") >>>print(cyber_attacks["Common"]) ['Malware', 'Phishing', 'Spam']

11.3.2 Dictionary with Tuples as Values

Tuples are preferred for fixed sets of items that should remain constant — since tuples are immutable, they protect the stored information from accidental modification.

>>>country_info = { "India": ("IN", "+91", "Asia"), "United States": ("US", "+1", "North America"), "Japan": ("JP", "+81", "Asia"), "Germany": ("DE", "+49", "Europe"), "Nigeria": ("NG", "+234", "Africa"), "Brazil": ("BR", "+55", "South America"), "Australia": ("AU", "+61", "Australia") } >>>print(country_info["India"]) ('IN', '+91', 'Asia') >>>print(country_info["India"][0]) IN >>>print(country_info["Nigeria"][2]) Africa

11.3.3 Nested Dictionary

A nested dictionary contains another dictionary as its value — useful when one piece of information has several related details, such as employee records.

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"]) Name of Emp101: Sajimon Abraham >>>print("Phone of Emp102:", employee["Emp102"]["phone"]) Phone of Emp102: 9876501234
11.4

Updating and Managing Dictionary Data

A dictionary is a mutable data structure — its contents can be changed even after creation. Updating refers to modifying existing key–value pairs or adding new ones.

11.4.1 update() Method

Useful for merging one dictionary into another or adding multiple items at once. If the key exists, its value is updated; if not, a new key–value pair is added.

>>>inventory = {"Apples": 50, "Bananas": 100} >>>new_stock = {"Oranges": 75, "Apples": 60} >>>inventory.update(new_stock) >>>print(inventory) {'Apples': 60, 'Bananas': 100, 'Oranges': 75}

11.4.2 Adding a New Key-Value Pair

>>>inventory = {"Apples": 60, "Bananas": 100, "Oranges": 75} >>>inventory["Mulberry"] = 180 >>>print(inventory) {'Apples': 60, 'Bananas': 100, 'Oranges': 75, 'Mulberry': 180}

Assigning a value to a non-existent key automatically creates a new key–value pair — this is treated as an update because the dictionary's structure changes.

11.4.3 Updating Complete Values

>>>student = {"name": "Aisha", "scores": [85, 90, 92]} >>>student["scores"] = [95, 98, 100] >>>print(student) {'name': 'Aisha', 'scores': [95, 98, 100]}

11.4.4 Removing a Key-Value Pair

>>>del inventory["Oranges"] >>>print(inventory) {'Apples': 60, 'Bananas': 100}

The del keyword removes a specific key and its value. If the key does not exist, del raises a KeyError.

11.5 · Live Tool

Dictionary Functions and Operations

Python provides several methods to remove, update, and retrieve information from dictionaries.

FunctionRemarks
keys()Returns a list-like view of all keys in the dictionary.
values()Returns a list-like view of all values in the dictionary.
items()Returns key–value pairs from the dictionary as tuples.
dictionary.update({key: value})Adds a new key–value pair or updates the value of an existing key.
dictionary.pop(key)Removes the specified key from the dictionary and returns its value.
dictionary.popitem()Removes and returns the last inserted key–value pair from the dictionary.

Try a Dictionary Method

● live
Pick a method, fill in the base dict and argument(s), then press Run.
update() / pop() take one argument: key:value for update, or just key for pop · keys()/values()/items()/popitem() need no argument.
11.6

An Application of Dictionary — Shopping Cart

A shopping cart is a real-world example where items and their quantities can be stored and processed efficiently. Using a dictionary ensures each item is listed only once, while quantity is updated whenever the same item is added again.

add_to_cart(cart, input_list)

Adds a new item to the shopping cart. If the item already exists in the dictionary, its quantity is increased; if not, the item is added as a new key with the quantity as its value.

def add_to_cart(cart, input_list): item = input_list[0] quantity = int(input_list[1]) if item in cart: cart[item] += quantity # Increase quantity if item already exists else: cart[item] = quantity # Add new item with its quantity

show_cart(cart)

Displays a complete summary of the cart: the number of different items, the total quantity of all products combined, and a tabular list of each item with its quantity.

def show_cart(cart): if not cart: print("Your cart is empty.") return print("\n------- Shopping Cart Summary -------") print("No. different items:", len(cart)) total_qty = sum(cart.values()) print("Total quantity of products:", total_qty) print("\nItems in your cart:") print("----------------------------") print("Item Name\tQuantity") print("----------------------------") for item, qty in cart.items(): print(f"{item}\t\t{qty}") print("----------------------------") # Main Program cart = {} n = int(input("How many items do you want to add to the cart? ")) for i in range(n): item_name = input(f"Enter item no {i+1}:") quantity = input("Enter quantity: ") user_input = [item_name, quantity] add_to_cart(cart, user_input) show_cart(cart) Run: How many items do you want to add to the cart? 5 Enter item no 1:Pen Enter quantity: 4 Enter item no 2:Book Enter quantity: 7 Enter item no 3:Bag Enter quantity: 2 Enter item no 4:Pen Enter quantity: 3 Enter item no 5:Book Enter quantity: 7 ------- Shopping Cart Summary ------- No. different items: 3 Total quantity of products: 23 Item Name Quantity ---------------------------- Pen 7 Book 14 Bag 2

The program is organised using functions, which makes the code clear, readable, and easy to maintain — add_to_cart() updates the dictionary on each entry, and show_cart() summarises it once all inputs are collected.

11.7

Set

A set is a collection of unique, unordered elements — its elements do not have fixed positions and cannot be accessed using indexes. Set elements must be immutable types such as numbers, strings, or tuples.

11.7.1 Creation of 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} >>>browsers = {"Chrome", "Firefox", "Safari", "Edge", "Opera", "Brave"} >>>print(browsers) {'Chrome', 'Opera', 'Edge', 'Brave', 'Safari', 'Firefox'} # set() converts a string into a set of unique characters >>>letters = set("balloon") >>>print(letters) {'b', 'n', 'a', 'l', 'o'}

{} makes a dictionary, not a set!

{} by itself creates an empty dictionary. To create an empty set, use the set() function: empty_set = set() — printing it displays set().

11.7.2 Set Functions and Operations

Given a = {1,2,3}, b = {3,4,5}, lng1 = {"Python","C","Java"}, lng2 = {"JavaScript","Python","Go"}:

Function / OperatorRemarksExample
union() or |Combines all unique elements from both sets.a|b → {1,2,3,4,5}
intersection() or &Returns elements common to both sets.a&b → {3}
difference() or -Elements in a set that are not in the other set.a-b → {1, 2}
add()Adds a single new element to a set.a.add(6)
remove()Removes an element from the set (error if not present).a.remove(3)
discard()Removes an element from the set (no error if missing).a.discard(10)
clear()Removes all elements from the set.a.clear() → set()

Sets are especially useful when we need to find common items or unique items — operations such as union, intersection, and difference are very efficient with sets.

11.7.2 – 11.7.3 · Live Tool

Set Operations Lab

Enter two comma-separated sets, pick an operation, and see how Python removes duplicates and computes the result.

Try a Set Operation

● live
Enter two sets, pick an operation, then press Run.
Duplicate entries within a set are removed automatically, just like in real Python sets — try typing Maths,Maths,Physics for set A.

Application: Finding Unique Words in a Sentence

A sentence is split into words using split(), then converted with set() to remove duplicates.

def get_sentence(): sentence = input("Enter a sentence: ") return sentence def show_unique_words(sentence): words = sentence.split() unique_words = set(words) print("Unique words:", unique_words) user_sentence = get_sentence() show_unique_words(user_sentence) Run: Enter a sentence: Hope brings hope and light brings light to every heart seeking change Unique words: {'brings', 'seeking', 'and', 'light', 'heart', 'to', 'Hope', 'hope', 'every', 'change'}

Since sets are unordered, the exact order of elements in the output may vary each time the program runs — and note that "Hope" and "hope" are treated as different words because Python strings are case-sensitive.

Let Us Do

Quick Recap

Tap a question to reveal the answer.

Why can't a list be used as a dictionary key?

Dictionary keys must be hashable — they need a fixed internal hash value that stays the same throughout their lifetime. Lists are mutable and can change after creation, so they cannot maintain a stable hash value, and are therefore not allowed as keys.

What is the difference between dictionary[key] and dictionary.get(key) when the key is missing?

dictionary[key] raises a KeyError if the key does not exist. dictionary.get(key) does not raise an error — it returns None, or a default value if one is supplied as a second argument.

Why are tuples preferred over lists for the values in country_info?

The country code, dialling code, and continent are fixed details that should not change. Tuples are immutable, so they protect this information from accidental modification — unlike lists, which are used when the stored data may need to change.

What does employee["Emp101"]["name"] mean in a nested dictionary?

It first looks up the key "Emp101" in the outer dictionary, which returns another dictionary. It then looks up the key "name" within that inner dictionary to retrieve the employee's name.

What happens when dictionary.update({key: value}) is called with a key that already exists?

The existing key's value is updated to the new value. If the key does not already exist, a new key–value pair is added to the dictionary instead.

What is the difference between pop(key) and popitem() on a dictionary?

pop(key) removes the specified key and returns its value. popitem() takes no key argument — it removes and returns the last inserted key–value pair as a tuple.

Why does {} create an empty dictionary and not an empty set?

Python reserves curly braces {} for dictionaries by default. To create an empty set, the set() function must be used instead — writing {} always produces an empty dictionary.

For a = {1,2,3} and b = {3,4,5}, what do a&b and a-b give?

a&b (intersection) gives {3} — the element common to both. a-b (difference) gives {1, 2} — the elements in a that are not in b.

What is the difference between remove() and discard() on a set?

Both remove an element from the set, but remove() raises an error if the element is not present, while discard() does nothing (no error) if the element is missing.

Why might the output of set("balloon") print its letters in a different order each time the program runs?

Sets are unordered collections in Python — they do not maintain a fixed sequence of elements, so the order in which the unique letters appear when printed is not guaranteed to be the same across runs.