🎉 Welcome to PyVerse! Start Learning Today

Dictionaries and Sets

Working with Dictionaries and Sets

Big idea

  • Dictionaries map keys to values (like a mini database).
  • Sets store unique items (like a bag that removes duplicates automatically).
  • Both are fast for lookups and great for solving real problems.

Part 1: Dictionaries

What is a dictionary?

  • A dictionary stores pairs: key -> value.
  • Keys must be unique and immutable (strings, numbers, tuples).
  • Values can be anything.
  • Think: a contact list where you look up a person (key) to get their phone number (value).

Create and use

Code:

book = {"title": "Wings of Fire", "pages": 320, "available": True} print(book["title"]) # Access by key -> Wings of Fire print(book.get("author", "Unknown"))# Safe access with a default -> Unknown book["pages"] = 325 # Update value book["author"] = "A. P. J. Abdul Kalam" # Add new key print(book)

Check existence and remove

Code:

scores = {"Ava": 88, "Ben": 92} print("Ava" in scores) # True (checks if key exists) removed = scores.pop("Ava") # Remove and get value # del scores["Ben"] # Remove without returning print(scores)

Useful methods and iteration

Code:

grades = {"Ava": 91, "Ben": 85, "Cara": 97} print(list(grades.keys())) # ['Ava', 'Ben', 'Cara'] print(list(grades.values())) # [91, 85, 97] print(list(grades.items())) # [('Ava', 91), ('Ben', 85), ('Cara', 97)] for name, score in grades.items(): print(name, "->", score) grades.update({"Ben": 89, "Dan": 78}) # Merge/update keys print(grades)

Counting with get (very common pattern)

Code:

word = "banana" freq = {} for ch in word: freq[ch] = freq.get(ch, 0) + 1 print(freq) # {'b': 1, 'a': 3, 'n': 2}

Dictionary comprehension (build a dict in one line)

Code:

nums = [1, 2, 3, 4, 5] squares_of_evens = {n: n*n for n in nums if n % 2 == 0} print(squares_of_evens) # {2: 4, 4: 16}

Common pitfalls

  • {} creates an empty dictionary, not a set.
  • Keys must be immutable: use a tuple for a key like (row, col), not a list.

Part 2: Sets

What is a set?

  • An unordered collection of unique items.
  • Great for removing duplicates and for math-like operations (union, intersection).

Create and use

Code:

animals = {"cat", "dog", "cat", "bird"} # duplicates are removed print(animals) # {'cat', 'dog', 'bird'} empty_set = set() # {} would be an empty dict

Membership and changing sets

Code:

students = {"Ava", "Ben", "Cara"} print("Ava" in students) # True students.add("Dan") # Add one students.update(["Eli", "Fay"]) # Add many students.discard("Zoe") # Remove if present (no error) # students.remove("Zoe") # Would raise an error if not present one = students.pop() # Remove and return a random item print(students)

Set operations (power tools)

Code:

day1 = {"Ava", "Ben", "Cara"} day2 = {"Ben", "Dan", "Cara"} print(day1 & day2) # intersection -> {'Ben', 'Cara'} print(day1 | day2) # union -> {'Ava', 'Ben', 'Cara', 'Dan'} print(day1 - day2) # difference -> {'Ava'} print(day1 ^ day2) # symmetric difference -> {'Ava', 'Dan'}

Set comprehension

Code:

letters = {ch for ch in "hello world" if ch.isalpha()} print(letters) # unique letters in the phrase

Part 3: Using dictionaries and sets together

Example: students and clubs

Code:

clubs = { "Ava": {"Chess", "Robotics"}, "Ben": {"Art", "Chess"}, "Cara": {"Robotics"} } # All clubs offered: all_clubs = set().union(*clubs.values()) print("All clubs:", all_clubs) # Who is in Chess? chess_members = {name for name, cset in clubs.items() if "Chess" in cset} print("Chess members:", chess_members) # Who shares at least one club with Ava? shared_with_ava = {name for name, cset in clubs.items() if name != "Ava" and (cset & clubs["Ava"])} print("Shares a club with Ava:", shared_with_ava)

Mini Project: Text Analyzer (Dictionaries + Sets)

Goal

  • Ask for a paragraph of text.
  • Count how many times each word appears (dictionary).
  • Find how many unique words there are (set).
  • Show the top 5 most common words.
  • Show which vowels appear in the text.

Steps

  1. Get text and lowercase it.
  2. Remove punctuation and split into words.
  3. Build a word->count dictionary.
  4. Build a set of unique words.
  5. Sort counts to find the top 5.
  6. Use a set to find which vowels appear.

Starter code

import string text = input("Enter a paragraph:\n> ") # 1) lowercase clean = text.lower() # 2) remove punctuation (simple approach) for ch in string.punctuation: clean = clean.replace(ch, " ") words = [w for w in clean.split() if w] # 3) word counts (dictionary) counts = {} for w in words: counts[w] = counts.get(w, 0) + 1 # 4) unique words (set) unique_words = set(words) # 5) top 5 most common words top5 = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:5] # 6) vowels present (sets) letters_present = {ch for ch in clean if ch.isalpha()} vowels_present = letters_present & set("aeiou") print("\nResults") print("Total words:", len(words)) print("Unique words:", len(unique_words)) print("Top 5 words:", top5) print("Vowels present:", sorted(vowels_present))

Try it out with a sample:

Input: "This is a test. This test is only a test!"

Output will show total words, unique words, top words like ('test', 3), ('is', 2), ('a', 2), and which vowels appear.

Challenges

  • Ignore very short words (like "a", "an", "the") when listing top words.
  • Show the average word length.
  • Print the longest words without duplicates.

Quick recap

Dictionaries

  • Store key->value pairs.
  • Fast lookups by key.
  • Useful methods: get, update, pop, keys, values, items.
  • Great for counting and mapping.

Sets

  • Store unique items.
  • Fast membership checks.
  • Powerful operations: union, intersection, difference, symmetric difference.
  • Great for removing duplicates and comparing groups.

Together

  • Use dictionaries to map things.
  • Use sets to handle uniqueness and group operations.
  • Combine them to answer real questions quickly and clearly.

You've learned tools that make your programs cleaner, faster, and smarter. Try using dictionaries and sets in your next project—once you start, you'll see them everywhere!

Loading quizzes...