Python Lecture 4: Dictionaries and Sets
1. Dictionaries in Python
What is a Dictionary?
A dictionary stores data in key-value pairs.
# Creating a dictionary
student = {
"name": "Alice",
"cgpa": 9.2,
"marks": [90, 95, 85]
}
print(student)
Accessing & Adding Data
# Accessing values
print(student["name"]) # Output: Alice
# Adding a new key-value pair
student["age"] = 20
print(student)
Dictionary Methods with Example:
myDict = {
"name": "Bob",
"age": 21,
"city": "Delhi"
}
print(myDict.keys()) # dict_keys(['name', 'age', 'city'])
print(myDict.values()) # dict_values(['Bob', 21, 'Delhi'])
print(myDict.items()) # dict_items([('name', 'Bob'), ('age', 21), ('city',
'Delhi')])
print(myDict.get("age")) # Output: 21
newData = {"age": 22, "college": "XYZ"}
myDict.update(newData)
print(myDict)
Nested Dictionary
student = {
"name": "John",
"score": {
"math": 95,
Python Lecture 4: Dictionaries and Sets
"science": 89
}
}
print(student["score"]["math"]) # Output: 95
Practice Problem 1: Word Meanings
word_meanings = {
"table": ["a piece of furniture", "list of facts & figures"],
"cat": "a small animal"
}
print(word_meanings)
Practice Problem 2: Count Unique Subjects (Use Set)
subjects = ["python", "java", "C++", "python", "javascript", "java", "python", "java",
"C++", "C"]
unique_subjects = set(subjects)
print("Classrooms needed:", len(unique_subjects)) # Output: 5
Practice Problem 3: Store Subject Marks in Dictionary
marks = {}
for i in range(3):
subject = input("Enter subject name: ")
mark = int(input("Enter marks: "))
marks[subject] = mark
print(marks)
2. Sets in Python
What is a Set?
A set is an unordered collection of unique elements.
# Creating sets
nums = {1, 2, 3, 4}
set2 = {1, 2, 2, 2} # duplicates will be removed
print(nums) # Output: {1, 2, 3, 4}
print(set2) # Output: {1, 2}
Set Methods with Example:
a = {1, 2, 3}
b = {3, 4, 5}
Python Lecture 4: Dictionaries and Sets
a.add(10)
print(a) # {1, 2, 3, 10}
a.remove(2)
print(a) # {1, 3, 10}
copy_set = a.copy()
copy_set.clear()
print(copy_set) # set()
print(a.pop()) # Removes a random element
print(a)
print(a.union(b)) # {1, 3, 4, 5, 10}
print(a.intersection(b)) # {3}
Practice Problem: Store 9 and 9.0 Separately
s = set()
s.add(9)
s.add("9.0") # store 9.0 as string
print(s) # Output: {9, '9.0'}
Summary Table:
| Topic | Code Feature | Example
|
|------------------------|----------------------------------|---------------------------
---------------|
| Dictionary Access | dict["key"] | student["name"]
|
| Add Key-Value | dict["key"] = value | student["age"] = 20
|
| Dictionary Methods | .keys(), .values() etc. | myDict.items()
|
| Nested Dictionary | dict["key1"]["key2"] | student["score"]["math"]
|
| Set Creation | set() or {1, 2, 3} | s = {1, 2, 3}
|
| Set Methods | .add(), .remove() etc. | s.add(5)
|
| Unique Counting | set(list) | len(set(subjects))
|