How to Use Dictionaries and Sets in Python for Beginners

Introduces Python dictionaries and sets with practical examples including creating, modifying, and performing set operations, plus a word-frequency counter.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 15 views 0 copies

Python code

37 lines
Python 3.9+
def demonstrate_dict_sets():
    # Create a dictionary with basic info
    person = {
        "name": "Alice",
        "age": 30,
        "city": "New York"
    }
    print("Dictionary:", person)

    # Access and modify dictionary values
    person["age"] = 31
    person["email"] = "alice@example.com"
    print("After updates:", person)

    # Create a set of unique items
    hobbies = {"reading", "hiking", "cooking", "hiking"}  # duplicates removed
    print("Set:", hobbies)

    # Dictionary operations
    print("Keys:", list(person.keys()))
    print("Values:", list(person.values()))
    print("Has 'age'?", "age" in person)

    # Set operations
    other_hobbies = {"hiking", "gaming", "painting"}
    print("Common hobbies:", hobbies.intersection(other_hobbies))
    print("All hobbies:", hobbies.union(other_hobbies))

    # Practical use: count word frequencies
    text = "the quick brown fox jumps over the lazy dog"
    word_counts = {}
    for word in text.split():
        word_counts[word] = word_counts.get(word, 0) + 1
    print("Word counts:", word_counts)

if __name__ == "__main__":
    demonstrate_dict_sets()

Output

stdout
Dictionary: {'name': 'Alice', 'age': 30, 'city': 'New York'}
After updates: {'name': 'Alice', 'age': 31, 'city': 'New York', 'email': 'alice@example.com'}
Set: {'reading', 'hiking', 'cooking'}
Keys: ['name', 'age', 'city', 'email']
Values: ['Alice', 31, 'New York', 'alice@example.com']
Has 'age'? True
Common hobbies: {'hiking'}
All hobbies: {'reading', 'hiking', 'cooking', 'gaming', 'painting'}
Word counts: {'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1}

How it works

Python dictionaries store key-value pairs and maintain insertion order as of Python 3.7. Sets automatically remove duplicate elements, making them ideal for uniqueness checks. The dict.get(key, default) method safely retrieves a value and handles missing keys without raising errors. The .intersection() and .union() methods return new sets and can be used on sets of any size. Word frequency counting is a classic pattern that transforms text into a dictionary of counts, useful for many text-processing tasks.

Common mistakes

  • Forgetting that sets are unordered, so print order may vary
  • Using a set when you need to track duplicates or order
  • Trying to access a dictionary key that doesn't exist without using .get() or checking with 'in'

Variations

  1. Use `collections.Counter(text.split())` for a more concise word count
  2. Use `hobbies & other_hobbies` and `hobbies | other_hobbies` for set operations

Real-world use cases

  • Counting unique users or IP addresses in a web server log to detect anomalies.
  • Building a tag mapping in an e-commerce system to match products to categories.
  • Processing survey responses by tracking how many times each option was selected.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.