Python Series track

Week 07 · Basic Track

Week 7 — Dictionaries & Sets

Use dictionaries for key-value storage and sets for unique collections. Learn dict comprehensions, set algebra, and when to choose each structure.

Basic Track2 min readFree lesson

Level: Basic | Prerequisite: Week 6 (Lists, Tuples)

Learning Goals

  • Creating dictionaries, accessing keys, modification
  • Commonly used methods (get, items, keys)
  • Set operations (Union/Intersection/Difference)
  • Criteria for choosing data structures

1. What is a dictionary

Mapping of key → value. No order (from 3.7+ insertion order is maintained). Braces {...}.

student = {"name": "Hong Gil-dong", "age": 20, "major": "CS"}

print(student["name"])      #Hong Gil-dong
student["age"] = 21         #Edit
student["email"] = "..."    #Add
del student["major"]        #Delete

Keys are usually strings or numbers, values can be of any type.

2. Commonly used methods

d = {"a": 1, "b": 2, "c": 3}

print(d.keys())     # dict_keys(['a', 'b', 'c'])
print(d.values())   # dict_values([1, 2, 3])
print(d.items())    # dict_items([('a', 1), ...])

#get: Safe retrieval (no error even if key is missing)
print(d.get("z"))            # None
print(d.get("z", "Default value"))  #Default value

#in: Check for key existence
print("a" in d)     # True

3. Iterating through dictionaries

for key in d:                    #Only key
    print(key)

for key, value in d.items():     #Key-value simultaneously
    print(f"{key} = {value}")

4. Sets

Collection of unique elements. No order. Braces {...} (however, empty set is set()).

fruits = {"Apple", "Banana", "Grape"}
fruits.add("Strawberry")
fruits.discard("Banana")    #Ignore if not present
print(len(fruits))

#Automatically remove duplicates
nums = [1, 2, 2, 3, 3, 3]
unique = set(nums)         # {1, 2, 3}

5. Set operations

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)    #Union {1,2,3,4,5,6}
print(a & b)    #Intersection {3,4}
print(a - b)    #Difference {1,2}
print(a ^ b)    #Symmetric Difference {1,2,5,6}

6. Criteria for choosing data structures

Situation Choice
Order matters, access by index List
Unchangeable, fast Tuple
Lookup by key Dictionary
Remove duplicates, check membership Set

Key Examples (examples/)

File Content
01_dict_basic.py Dictionary Create/Edit
02_dict_methods.py Use get, items, in
03_set.py Set creation and operations
04_word_count.py Word frequency count

⚠️ Common Mistakes

  1. Accessing a non-existent key
    d = {"a": 1}
    print(d["z"])    # KeyError
    

→ Use d.get("z") or if "z" in d:.

  1. Create an empty set with {}

    s = {}    #Empty dictionary!
    s = set() #Empty set
    
  2. Put a list into a set

    {[1, 2]}    # TypeError: unhashable type: 'list'
    {(1, 2)}    #The tuple is OK
    
  3. Modify while iterating over a dictionary

    for k in d:
        del d[k]   # RuntimeError
    

→ Copy the key list in advance: for k in list(d):.

❓ FAQ

Q1. What if dictionary keys are duplicated? A. Overwritten by the last value. Keys must be unique.

Q2. Are dictionaries ordered? A. From Python 3.7+, insertion order is maintained. Sorting is sorted(d.items()).

Q3. How to distinguish if both sets and dictionaries are {}? A. If there is :, it’s a dictionary; if not, it’s a set. {1, 2} = set, {1: "a"} = dict.

📝 Exercises (exercises/)

  • exercise1.md — Contacts (dictionary)
  • exercise2.md — Word frequency Top 3
  • exercise3.md — Remove duplicates (maintain order)

Next Week

Week 8. Handling Strings — Master string methods

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

examples/01_dict_basic.pyPython
student = {"name": "Hong Gil-dong", "age": 20, "major": "CS"}

print(student["name"])
print(student["age"])

student["age"] = 21
student["email"] = "[email protected]"
print(student)

del student["major"]
print(student)
examples/02_dict_methods.pyPython
d = {"a": 1, "b": 2, "c": 3}

print(list(d.keys()))
print(list(d.values()))
print(list(d.items()))

#get: Safety check
print(d.get("z"))
print(d.get("z", "None"))

# in
print("a" in d)
print("z" in d)

#Patrol
for key, value in d.items():
    print(f"{key} = {value}")
examples/03_set.pyPython
fruits = {"Apple", "Banana", "Grape"}
fruits.add("Strawberry")
fruits.discard("Nonexistent fruit")  #No error
print(fruits)

#Remove duplicates
nums = [1, 2, 2, 3, 3, 3]
print(set(nums))   # {1, 2, 3}

#Set operation
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print("Union:", a | b)
print("Intersection:", a & b)
print("Difference:", a - b)
print("Symmetric difference:", a ^ b)
examples/04_word_count.pyPython
text = "apple banana apple grape banana apple"
words = text.split()

count = {}
for word in words:
    count[word] = count.get(word, 0) + 1

print(count)
# {'apple': 3, 'banana': 2, 'grape': 1}

Assignment

Goal

Find a phone number by name using Save/Retrieve/Delete CLI.

Requirements

  • Data: Dictionary in {"Name": "Phone Number"} format
  • Commands: add, find, del, list, quit
  • If name not found in find, display "Cannot find"

Input/Output Example

Command: add
Name: Hong Gil-dong
Phone: 010-1234-5678
Added

Command: find
Name: Hong Gil-dong
Hong Gil-dong: 010-1234-5678

Command: list
1. Hong Gil-dong: 010-1234-5678

Assignment 2. Top 3 Word Frequencies

Goal

Print the 3 most frequently appearing words in a long sentence.

Requirements

  • Input as a variable inside the code (long sentence)
  • Words are separated by spaces
  • Sort by descending frequency, top 3

Input/Output Example

1. apple: No. 5
2. banana: No. 3
3. cherry: No. 2

Challenge

  • Case-insensitive
  • Ignore punctuation such as periods and commas

Assignment 3. Remove Duplicates (Preserve Order)

Goal

Remove duplicates from a list while maintaining the original input order.

Requirements

  • Input: ["a", "b", "a", "c", "b", "d"]
  • Output: ["a", "b", "c", "d"]
  • If you only use set(), the order may break → use a dictionary

Hint

In Python 3.7+, dictionaries maintain the order of input. dict.fromkeys(list) can be used.

Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

solution1.pyPython
contacts = {}

while True:
    cmd = input("Command (add/find/del/list/quit):").strip()
    if cmd == "quit":
        break
    elif cmd == "add":
        name = input("Name:")
        phone = input("Phone:")
        contacts[name] = phone
        print("Added")
    elif cmd == "find":
        name = input("Name:")
        if name in contacts:
            print(f"{name}: {contacts[name]}")
        else:
            print("Cannot be found")
    elif cmd == "del":
        name = input("Name:")
        if name in contacts:
            del contacts[name]
            print("Deleted")
        else:
            print("Name does not exist")
    elif cmd == "list":
        for i, (name, phone) in enumerate(contacts.items(), 1):
            print(f"{i}. {name}: {phone}")
solution2.pyPython
text = "apple banana apple cherry banana apple cherry apple banana apple cherry banana apple"

count = {}
for word in text.split():
    count[word] = count.get(word, 0) + 1

#Sort by frequency in descending order
top3 = sorted(count.items(), key=lambda x: -x[1])[:3]
for i, (word, c) in enumerate(top3, 1):
    print(f"{i}. {word}: {c} times")
solution3.pyPython
data = ["a", "b", "a", "c", "b", "d"]

#Method 1: Loop and handle manually
seen = set()
result = []
for x in data:
    if x not in seen:
        seen.add(x)
        result.append(x)
print(f"Method 1: {result}")

#Method 2: Use dict.fromkeys (Python 3.7+)
result2 = list(dict.fromkeys(data))
print(f"Method 2: {result2}")

Learn this lesson with a mentor

Work through the Python Series track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now