⬅ Previous Next ➡

Dictionaries and Sets

Dictionary and Set (Basics)
  • Dictionary: key-value pairs, mutable, unordered (in old versions), uses {key: value}
  • Set: unique elements only, mutable, unordered, uses {} (empty set is set())
  • Keys in dict must be unique and immutable types (int, str, tuple etc.).
student = {"name": "Sourav", "age": 25}
nums_set = {10, 20, 20, 30}

print(student)
print(nums_set)
Dictionary Creation
  • Create using {} or dict().
  • Duplicate keys overwrite previous value.
d1 = {"a": 1, "b": 2}
d2 = dict(name="Sourav", course="Python")
d3 = {}   # empty dict

print(d1)
print(d2)
print(d3)
Accessing Dictionary Elements
  • Use dict[key] to access value (KeyError if key missing).
  • Use get(key, default) to avoid error.
student = {"name": "Sourav", "age": 25}

print(student["name"])
print(student.get("age"))
print(student.get("city", "Not Found"))
Dictionary Methods (Common)
  • keys() → all keys
  • values() → all values
  • items() → (key, value) pairs
  • update() → add/modify multiple
  • pop(key) → remove by key
  • popitem() → remove last inserted pair
  • clear() → remove all
d = {"a": 10, "b": 20}

d["c"] = 30
d.update({"b": 99, "d": 40})
print(d)

print(d.keys())
print(d.values())
print(d.items())

d.pop("a")
print(d)
Nested Dictionary (Nested Structures)
  • Dictionary can store lists, tuples, sets, and even dictionaries.
  • Nested access uses multiple keys/indexes.
data = {
    "student": {
        "name": "Sourav",
        "marks": [80, 90, 85]
    },
    "active": True
}

print(data["student"]["name"])
print(data["student"]["marks"][1])
Iteration in Dictionary
  • Iterate keys by default.
  • Use items() for key-value together.
student = {"name": "Sourav", "age": 25, "course": "Python"}

for key in student:
    print(key, student[key])

for k, v in student.items():
    print(k, "=>", v)
Set Creation
  • Set stores unique elements only.
  • Empty set must be created using set() (because {} makes empty dict).
s1 = {1, 2, 3, 3}
s2 = set([10, 20, 20, 30])
s3 = set()     # empty set

print(s1)      # {1, 2, 3}
print(s2)
print(s3)
Set Methods (Common)
  • add(x) → add one item
  • update(iterable) → add many items
  • remove(x) → error if not found
  • discard(x) → no error if not found
  • pop() → removes random item
  • clear() → removes all items
s = {1, 2, 3}

s.add(4)
s.update([5, 6])
s.discard(2)
print(s)

s.remove(3)
print(s)
Set Operations (Union, Intersection, Difference)
  • | union, & intersection, - difference, ^ symmetric difference
  • Same operations with methods: union(), intersection(), difference(), symmetric_difference()
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)    # union
print(a & b)    # intersection
print(a - b)    # difference
print(a ^ b)    # symmetric difference
Frozen Set (Immutable Set)
  • frozenset is an immutable (read-only) set.
  • Cannot add/remove elements after creation.
  • Supports set operations (union, intersection etc.).
fs = frozenset([1, 2, 3, 3])
print(fs)

# fs.add(4)   # Error: frozenset has no add()

a = frozenset([1, 2, 3])
b = frozenset([3, 4, 5])

print(a | b)
print(a & b)
⬅ Previous Next ➡