Dictionaries
A dictionary (dict) is a data structure that stores key-value pairs. Let's explore its pratcical usage.
Creating Dictionaries
Using the dict() constructor:
person = dict(name="Alice", age=30, city="New York")
print(person) # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}
Using curly braces:
person = {"name": "Alice", "age": 30, "city": "New York"}
print(person) # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}
From a sequence of pairs:
data = [('name', 'Alice'), ('age', 30), ('city', 'New York')]
person = dict(data)
print(person) # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}
Using dictionary comprehension:
squares = {x: x**2 for x in (1, 3, 5)}
print(squares) # Output: {1: 1, 3: 9, 5: 25}
Accessing, Adding, Modifying, and Deleting Elements
Accessing values:
person = {"name": "Alice", "age": 30, "city": "New York"}
print(person["name"]) # Output: Alice
Using get() to avoid KeyError:
print(person.get("country", "Unknown")) # Output: Unknown
Adding new key-value pairs:
person = dict()
person["name"] = "Alice"
person["age"] = 30
print(person) # Output: {'name': 'Alice', 'age': 30}
Modifying values:
person["age"] = 31
print(person) # Output: {'name': 'Alice', 'age': 31}
Deleting elements:
- Using
pop():
person = {"name": "Alice", "age": 30, "city": "New York"}
age = person.pop("age")
print(age) # Output: 30
print(person) # Output: {'name': 'Alice', 'city': 'New York'}
- Using
del:
del person["city"]
print(person) # Output: {'name': 'Alice'}
Setting default values:
person.setdefault("country", "USA")
print(person) # Output: {'name': 'Alice', 'country': 'USA'}
Sets
A set is an unordered collection of unique elements.
Creating Sets
Using curly braces:
tech_brands = {"Apple", "Google", "Microsoft"}
print(type(tech_brands)) # Output: <class 'set'>
print(tech_brands) # Output: {'Google', 'Apple', 'Microsoft'}
Using set() constructor:
empty_set = set()
print(empty_set) # Output: set()
fruits = set(["apple", "banana", "orange"])
print(fruits) # Output: {'orange', 'banana', 'apple'}
Adding and Removing Elements
Adding elements:
colors = set()
colors.add("red")
colors.add("blue")
print(colors) # Output: {'red', 'blue'}
Removing elements:
- Using
remove():
colors = {"red", "blue", "green"}
colors.remove("green")
print(colors) # Output: {'red', 'blue'}
- Handling missing keys with
discard():
colors.discard("yellow") # No error, even though 'yellow' doesn't exist
print(colors) # Output: {'red', 'blue'}
remove() raises a KeyError if the element is not present, while discard() silently does nothing.