Dictionaries and Sets

Dictionaries and Sets in Python

Introduction

Dictionaries and sets are powerful data structures in Python. Dictionaries store key-value pairs, while sets store unique unordered elements.

Dictionaries

Dictionaries are collections of key-value pairs, where each key must be unique.

python
1
# Creating a dictionary
2
person = {
3
'name': 'John',
4
'age': 30,
5
'city': 'New York'
6
}
7
8
# Accessing values
9
print(person['name']) # Output: John
Loading tool...

Try working with dictionaries

Create a dictionary

person = { 'name': 'John', 'age': 30, 'city': 'New York' }

Access and print values

print("Name:", person['name']) print("Age:", person['age'])

Add a new key-value pair

person['job'] = 'Developer' print("\nUpdated dictionary:", person)

Modify an existing value

person['age'] = 31 print("After modification:", person) [/tool]

Sets

Sets are unordered collections of unique elements.

python
1
# Creating a set
2
numbers = {1, 2, 3, 4, 5}
3
4
# Adding elements
5
numbers.add(6)
6
7
# Removing duplicates automatically
8
numbers.add(1) # Won't add duplicate
Loading tool...

Working with sets

Create a set

numbers = {1, 2, 3, 4, 5} print("Original set:", numbers)

Add elements

numbers.add(6) print("After adding 6:", numbers)

Try adding a duplicate

numbers.add(1) print("After adding duplicate 1:", numbers)

Set operations

other_numbers = {4, 5, 6, 7, 8} print("\nOther set:", other_numbers) print("Union:", numbers | other_numbers) print("Intersection:", numbers & other_numbers) [/tool]

Key Features

Dictionaries

  1. Key-value mapping
  2. Fast lookups
  3. Mutable
  4. Keys must be unique and immutable

Sets

  1. Unordered collection
  2. No duplicates
  3. Fast membership testing
  4. Mathematical set operations

Practice Exercise

Loading tool...

Practice with dictionaries and sets

Dictionary operations

student = { 'name': 'Alice', 'grades': [85, 92, 78], 'subjects': ['Math', 'Science', 'History'] }

1. Add a new grade

student['grades'].append(95) print("Updated grades:", student['grades'])

2. Calculate average grade

average = sum(student['grades']) / len(student['grades']) print("Average grade:", average)

Set operations

math_students = {'Alice', 'Bob', 'Charlie'} science_students = {'Bob', 'Diana', 'Alice'}

3. Find students taking both subjects

both_subjects = math_students & science_students print("\nStudents taking both subjects:", both_subjects)

4. Find all unique students

all_students = math_students | science_students print("All unique students:", all_students) [/tool]