Dictionaries and Sets

Dictionaries and Sets

Dictionaries

Creating Dictionaries

# Empty dictionary
person = {}

With values

person = { "name": "John", "age": 30, "city": "London" }

Accessing Values

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

print(person["name"]) # John print(person.get("city")) # London

Default value if key not found

print(person.get("country", "UK")) # UK

Modifying Dictionaries

person = {"name": "John"}

person["age"] = 31 # Add/update person["country"] = "UK" # Add new

del person["age"] # Delete

Dictionary Methods

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

print(person.keys()) # dict_keys(['name', 'age']) print(person.values()) # dict_values(['John', 30]) print(person.items()) # dict_items([('name', 'John'), ('age', 30)])

Update

person.update({"age": 31, "city": "London"})

Iterating

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

for key in person: print(f"{key}: {person[key]}")

for key, value in person.items(): print(f"{key}: {value}")

Sets

Creating Sets

# Empty set
numbers = set()

With values

fruits = {"apple", "banana", "cherry"}

Set Operations

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

print(set1.union(set2)) # {1, 2, 3, 4, 5, 6} print(set1.intersection(set2)) # {3, 4} print(set1.difference(set2)) # {1, 2} print(set1.symmetric_difference(set2)) # {1, 2, 5, 6}

Set Methods

fruits = {"apple", "banana"}

fruits.add("cherry") # Add element fruits.remove("apple") # Remove (raises error if not found) fruits.discard("grape") # Remove (silent if not found) fruits.clear() # Clear all

Summary

  • Dictionaries: key-value pairs, fast lookup
  • Sets: unique unordered elements, great for membership tests

Next Lesson

In the next lesson, you'll learn about functions.

Quiz - Quiz - Dictionaries and Sets

1. How do you access value 'John' in {'name': 'John'}?

2. What is unique about sets?

3. How do you check if a key exists in a dictionary?

Lists and Tuples