Python Intermediate

Python Dictionaries and Sets: Key-Value Pairs and Unique Collections

CodingerWeb
CodingerWeb
22 views 40 min read

Understanding Python Dictionaries and Sets

Dictionaries store key-value pairs, while sets store unique elements. Both are powerful data structures for different use cases.

Python Dictionaries

Dictionaries are unordered collections of key-value pairs:


# Creating dictionaries
empty_dict = {}
also_empty = dict()

# Dictionary with data
person = {
    "name": "Alice",
    "age": 30,
    "city": "New York",
    "occupation": "Engineer"
}

print(person)  # {'name': 'Alice', 'age': 30, 'city': 'New York', 'occupation': 'Engineer'}

# Different data types as values
mixed_dict = {
    "string": "hello",
    "number": 42,
    "list": [1, 2, 3],
    "boolean": True
}

Accessing Dictionary Values


person = {"name": "Alice", "age": 30, "city": "New York"}

# Access by key
print(person["name"])  # Alice
print(person["age"])   # 30

# Using get() method (safer)
print(person.get("name"))        # Alice
print(person.get("country"))     # None
print(person.get("country", "USA"))  # USA (default value)

# Check if key exists
if "age" in person:
    print(f"Age: {person['age']}")

# Get all keys, values, or items
print(person.keys())    # dict_keys(['name', 'age', 'city'])
print(person.values())  # dict_values(['Alice', 30, 'New York'])
print(person.items())   # dict_items([('name', 'Alice'), ('age', 30), ('city', 'New York')])

Modifying Dictionaries


person = {"name": "Alice", "age": 30}

# Add or update items
person["city"] = "New York"     # Add new key-value pair
person["age"] = 31              # Update existing value
print(person)  # {'name': 'Alice', 'age': 31, 'city': 'New York'}

# Update multiple items
person.update({"occupation": "Engineer", "salary": 75000})
print(person)

# Remove items
del person["salary"]            # Remove by key
removed_value = person.pop("occupation")  # Remove and return value
print(f"Removed: {removed_value}")

# Clear all items
# person.clear()

Dictionary Methods and Operations


# Dictionary comprehension
squares = {x: x**2 for x in range(1, 6)}
print(squares)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# Filtering with comprehension
even_squares = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print(even_squares)  # {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}

# Iterating through dictionaries
person = {"name": "Alice", "age": 30, "city": "New York"}

# Iterate through keys
for key in person:
    print(f"{key}: {person[key]}")

# Iterate through key-value pairs
for key, value in person.items():
    print(f"{key}: {value}")

# Nested dictionaries
students = {
    "alice": {"age": 20, "grade": "A", "subjects": ["Math", "Physics"]},
    "bob": {"age": 21, "grade": "B", "subjects": ["Chemistry", "Biology"]},
    "charlie": {"age": 19, "grade": "A", "subjects": ["Math", "Chemistry"]}
}

print(students["alice"]["grade"])  # A
print(students["bob"]["subjects"][0])  # Chemistry

Python Sets

Sets are unordered collections of unique elements:


# Creating sets
empty_set = set()  # Note: {} creates an empty dictionary, not set
numbers = {1, 2, 3, 4, 5}
fruits = {"apple", "banana", "orange"}

print(numbers)  # {1, 2, 3, 4, 5}
print(fruits)   # {'apple', 'banana', 'orange'}

# Create set from list (removes duplicates)
numbers_list = [1, 2, 2, 3, 3, 3, 4, 5]
unique_numbers = set(numbers_list)
print(unique_numbers)  # {1, 2, 3, 4, 5}

# Create set from string
letters = set("hello")
print(letters)  # {'h', 'e', 'l', 'o'}

Set Operations


# Adding and removing elements
fruits = {"apple", "banana"}

fruits.add("orange")
print(fruits)  # {'apple', 'banana', 'orange'}

fruits.update(["grape", "kiwi"])  # Add multiple items
print(fruits)

fruits.remove("banana")    # Raises error if item doesn't exist
fruits.discard("mango")    # No error if item doesn't exist
print(fruits)

# Set operations
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Union (all elements from both sets)
union = set1 | set2  # or set1.union(set2)
print(f"Union: {union}")  # {1, 2, 3, 4, 5, 6, 7, 8}

# Intersection (common elements)
intersection = set1 & set2  # or set1.intersection(set2)
print(f"Intersection: {intersection}")  # {4, 5}

# Difference (elements in set1 but not in set2)
difference = set1 - set2  # or set1.difference(set2)
print(f"Difference: {difference}")  # {1, 2, 3}

# Symmetric difference (elements in either set, but not both)
sym_diff = set1 ^ set2  # or set1.symmetric_difference(set2)
print(f"Symmetric difference: {sym_diff}")  # {1, 2, 3, 6, 7, 8}

Set Methods and Comparisons


set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}
set3 = {4, 5, 6}

# Check relationships
print(set1.issubset(set2))    # True (set1 is subset of set2)
print(set2.issuperset(set1))  # True (set2 is superset of set1)
print(set1.isdisjoint(set3))  # True (no common elements)

# Length and membership
print(len(set2))      # 5
print(3 in set1)      # True
print(6 not in set1)  # True

# Convert set to list
set_as_list = list(set1)
print(set_as_list)  # [1, 2, 3] (order may vary)

Practical Examples


# Example 1: Word frequency counter
def count_words(text):
    """Count frequency of words in text"""
    words = text.lower().split()
    word_count = {}
    
    for word in words:
        # Remove punctuation
        word = word.strip(".,!?;:")
        if word:
            word_count[word] = word_count.get(word, 0) + 1
    
    return word_count

text = "Python is great. Python is powerful. Python is easy to learn."
result = count_words(text)
print(result)  # {'python': 3, 'is': 3, 'great': 1, 'powerful': 1, 'easy': 1, 'to': 1, 'learn': 1}

# Example 2: Remove duplicates while preserving order
def remove_duplicates(items):
    """Remove duplicates while preserving order"""
    seen = set()
    result = []
    
    for item in items:
        if item not in seen:
            seen.add(item)
            result.append(item)
    
    return result

numbers = [1, 2, 3, 2, 4, 3, 5, 1]
unique = remove_duplicates(numbers)
print(unique)  # [1, 2, 3, 4, 5]

Practice Exercise

Create a student grade management system:


def grade_manager():
    """Student grade management system"""
    students = {}
    
    while True:
        print("
--- Grade Manager ---")
        print("1. Add student")
        print("2. Add grade")
        print("3. View student grades")
        print("4. Calculate average")
        print("5. View all students")
        print("6. Find top performers")
        print("7. Quit")
        
        choice = input("Choose an option (1-7): ")
        
        if choice == "1":
            name = input("Enter student name: ").strip().title()
            if name not in students:
                students[name] = []
                print(f"Added student: {name}")
            else:
                print(f"{name} already exists!")
                
        elif choice == "2":
            name = input("Enter student name: ").strip().title()
            if name in students:
                try:
                    grade = float(input("Enter grade (0-100): "))
                    if 0 <= grade <= 100:
                        students[name].append(grade)
                        print(f"Added grade {grade} for {name}")
                    else:
                        print("Grade must be between 0 and 100!")
                except ValueError:
                    print("Please enter a valid number!")
            else:
                print(f"Student {name} not found!")
                
        elif choice == "3":
            name = input("Enter student name: ").strip().title()
            if name in students:
                if students[name]:
                    print(f"
{name}'s grades: {students[name]}")
                    avg = sum(students[name]) / len(students[name])
                    print(f"Average: {avg:.2f}")
                else:
                    print(f"{name} has no grades yet.")
            else:
                print(f"Student {name} not found!")
                
        elif choice == "4":
            if students:
                all_grades = []
                for grades in students.values():
                    all_grades.extend(grades)
                
                if all_grades:
                    overall_avg = sum(all_grades) / len(all_grades)
                    print(f"Overall class average: {overall_avg:.2f}")
                else:
                    print("No grades recorded yet!")
            else:
                print("No students added yet!")
                
        elif choice == "5":
            if students:
                print("
All students:")
                for name, grades in students.items():
                    if grades:
                        avg = sum(grades) / len(grades)
                        print(f"{name}: {len(grades)} grades, Average: {avg:.2f}")
                    else:
                        print(f"{name}: No grades")
            else:
                print("No students added yet!")
                
        elif choice == "6":
            if students:
                student_averages = {}
                for name, grades in students.items():
                    if grades:
                        student_averages[name] = sum(grades) / len(grades)
                
                if student_averages:
                    # Sort by average (descending)
                    top_students = sorted(student_averages.items(), 
                                        key=lambda x: x[1], reverse=True)
                    
                    print("
Top performers:")
                    for i, (name, avg) in enumerate(top_students[:3], 1):
                        print(f"{i}. {name}: {avg:.2f}")
                else:
                    print("No grades to analyze!")
            else:
                print("No students added yet!")
                
        elif choice == "7":
            print("Goodbye!")
            break
            
        else:
            print("Invalid choice! Please try again.")

# Run the grade manager
grade_manager()