Django

Dictionaries and Sets

Dictionaries and Sets in Python: Storing and Managing Unique Data

Python offers several ways to organize data. Two very useful built-in types are dictionaries and sets. They help you store data with fast access and enforce uniqueness where needed.

Let’s dive into what they are, how they work, and when to use them.


Dictionaries: Key-Value Stores

A dictionary stores data in key-value pairs — like a real dictionary where you look up a word (key) to get its meaning (value).

  • Keys must be unique and immutable (strings, numbers, tuples).

  • Values can be any data type.

  • Defined using curly braces {} with colon : separating keys and values.

Creating a Dictionary

python
student = {
"name": "Alice",
"age": 23,
"courses": ["Math", "Physics"]
}

Accessing and Modifying

python
print(student["name"]) # Alice
student["age"] = 24 # Update value
student["grade"] = "A" # Add new key-value pair

Useful Methods

  • .get(key, default) — safely get a value, returns default if key not found

  • .keys(), .values(), .items() — iterate over keys, values, or key-value pairs

  • .pop(key) — remove key and return its value


Sets: Unordered Collections of Unique Items

A set stores unique elements — no duplicates allowed. Great for membership tests and operations like unions and intersections.

  • Defined using curly braces {} or the set() function.

  • Elements must be immutable and unique.

  • No indexing because sets are unordered.

Creating a Set

python
fruits = {"apple", "banana", "orange"}
empty_set = set() # Note: {} creates an empty dict, not a set

Adding and Removing Elements

python
fruits.add("grape")
fruits.remove("banana") # raises KeyError if not found
fruits.discard("pear") # no error if not found

Set Operations

  • Union: Combine all elements

python
A = {1, 2, 3}
B = {3, 4, 5}
print(A | B) # {1, 2, 3, 4, 5}
  • Intersection: Elements common to both sets

python
print(A & B) # {3}
  • Difference: Elements in one set but not the other

python
print(A - B) # {1, 2}
  • Symmetric Difference: Elements in either set but not both

python
print(A ^ B) # {1, 2, 4, 5}

️ When to Use Which?

Structure Use Case
Dictionary When you need key-based lookup (e.g., user data)
Set When you need unique items or perform set math

Summary

Feature Dictionary Set
Syntax {"key": "value"} {"apple", "banana"}
Order Ordered (Python 3.7+) Unordered
Mutability Mutable Mutable
Duplicate keys/items No duplicate keys allowed No duplicate items allowed
Access By key Membership testing

Leave a Reply

Your email address will not be published. Required fields are marked *