Dictionary and Tuple
What is a Dictionary?
Dictionary and Tuple

What is a Dictionary?
A dictionary is an unordered collection of key-value pairs.
Each key must be unique and immutable (like string, number, tuple).
Values can be any Python data type.
Dictionaries are mutable, so you can change, add, or remove items.
# Empty dictionary
my_dict = {}
# Dictionary with items
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
# Dictionary with mixed types
data = {
"numbers": [1,2,3],
"flag": True,
"info": {"height": 170, "weight": 60}
}
Accessing Items
# Two ways to access values
print(person["name"]) # Alice
print(person.get("age")) # 25 (returns None if key doesn't exist)
Adding or Updating Items
person["email"] = "alice@example.com" # Add new key
person["age"] = 26 # Update existing key
Removing Items
Removing Items
person.pop("city") # Remove key and return value
person.popitem() # Remove last inserted key-value pair
del person["email"] # Delete a specific key
person.clear() # Remove all items
Iterating Over a Dictionary
for key in person:
print(key, person[key])
# Using items()
for key, value in person.items():
print(key, value)
Summary
Mutable Key-value pairs Keys must be unique and immutable Values can be any type
What is a Tuple?
A tuple is an ordered collection of items like a list, but immutable. Once created, you cannot change, add, or remove items. Tuples are often used for fixed data like coordinates, dates, or multiple return values.
Creating a Tuple
# Empty tuple
empty = ()
# Tuple with values
point = (10, 20)
# Tuple with mixed types
data = (1, "apple", True, 3.14)
# Single element tuple (note the comma!)
single = (5)
Accessing Tuple Items
print(point[0]) # 10
print(data[-1]) # 3.14
print(data[1:3]) # ("apple", True)
Tuple Operations
# Concatenation
t1 = (1,2)
t2 = (3,4)
t3 = t1 + t2 # (1,2,3,4)
# Repetition
t1 * 3 # (1,2,1,2,1,2)
# Membership
5 in t1 # False
Use cases for Dictionary and Tuple
Dictionary
###Counting Occurrences (Frequency Counter)
Dictionaries are ideal for counting items efficiently.
words = ["apple", "banana", "apple", "orange", "banana", "apple"]
count = {}
for word in words:
count[word] = count.get(word, 0) + 1
print(count)
# Output: {'apple': 3, 'banana': 2, 'orange': 1}
###You can store complex hierarchical data.
students = {
"Alice": {"age": 25, "grade": 90},
"Bob": {"age": 23, "grade": 85}
}
print(students["Alice"]["grade"]) # 90
# Dictionaries are perfect for application configurations.
config = {
"theme": "dark",
"font_size": 12,
"language": "English"
}
print(config["theme"]) # dark
#Swapping Keys and Values
grades = {"Alice": 90, "Bob": 85}
inverse = {v:k for k,v in grades.items()}
print(inverse) # {90: 'Alice', 85: 'Bob'}
# Merging Dictionaries
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = {**dict1, **dict2} # dict2 overwrites dict1 for duplicate keys
print(merged) # {'a': 1, 'b': 3, 'c': 4}
Tuple
1. Storing Fixed Collections of Items
Tuples are ideal for data that should not be modified.
point = (10, 20) # x, y coordinates
rgb = (255, 0, 0) # Red color in RGB
date = (2025, 10, 21) # Year, Month, Day
print(point[0]) # 10
Use Case: Coordinates, RGB colors, fixed dates, or any immutable data.
2. Returning Multiple Values from a Function
Tuples make it easy to return several values at once.
def get_name_and_age():
return "Alice", 25
name, age = get_name_and_age()
print(name, age) # Alice 25
3. Using Tuples as Dictionary Keys
Since tuples are immutable, they can be used as keys in dictionaries.
locations = {
(0, 0): "Origin",
(1, 2): "Point A"
}
print(locations[(1, 2)]) # Point A
4. Unpacking Sequences
Tuples allow easy unpacking of multiple items.
rgb = (255, 100, 50)
r, g, b = rgb
print(r, g, b) # 255 100 50
5. Named Tuples (Enhanced Tuples)
Python provides namedtuple for tuples with named fields, improving readability.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(10, 20)
print(p.x, p.y) # 10 20
6. Sequence Integrity (Preventing Changes)
If you want to protect data from accidental modification, use a tuple instead of a list.
colors = ("red", "green", "blue")
# colors[0] = "yellow" # ❌ This will raise an error
7. Packing and Unpacking
Tuples allow packing multiple items into one variable and unpacking them back.
# Packing
person = "Alice", 25, "New York"
# Unpacking
name, age, city = person
print(name, age, city) # Alice 25 New York
8. Iterating Through Tuples
Tuples can be iterated just like lists:
rgb = (255, 0, 0)
for color in rgb:
print(color)
Summary: When to Use Tuples
When you need immutable, fixed data For coordinates, RGB values, dates When returning multiple values from a function For dictionary keys or composite keys To prevent accidental data modification Useful with packing/unpacking and namedtuples
메타데이터
- post_id
- 9e0b87bf8e03
- slug
- dictionary-and-tuple-9e0b87bf8e03
- url
- https://medium.com/@sameenah.tm/dictionary-and-tuple-9e0b87bf8e03
- canonical_url
- https://medium.com/@sameenah.tm/dictionary-and-tuple-9e0b87bf8e03
- author_url
- https://medium.com/@sameenah.tm
- status
- ok
- fetched_at
- 2026-07-13 06:23:13