Back to blog
← View series: python tutorials

~/blog

Data Structures - Dictionaries & Tuples

Apr 1, 2026β€’5 min readβ€’By Mohammed Vasim
PythonProgrammingTutorialBeginner

Introduction

In this tutorial, you'll learn about two important data structures in Python: dictionaries and tuples. Dictionaries store data in key-value pairs, while tuples are immutable sequences. Both are essential tools for organizing and manipulating data.

What You'll Learn

  • Creating and using dictionaries
  • Accessing, adding, and modifying dictionary data
  • Dictionary methods
  • Creating and using tuples
  • Tuple unpacking
  • When to use each data structure

Dictionaries

Dictionaries store data in key-value pairs. Each key maps to a value, like a real dictionary maps words to definitions.

Creating Dictionaries

python
# Basic dictionary
person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

print(person)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

# Using dict() constructor
person2 = dict(name="Bob", age=30, city="Boston")
print(person2)
# Output: {'name': 'Bob', 'age': 30, 'city': 'Boston'}

Accessing Values

python
person = {"name": "Alice", "age": 25, "city": "New York"}

# Using keys
print(person["name"])     # Alice
print(person["age"])      # 25

# Using get() method (safer - returns None if key missing)
print(person.get("name"))         # Alice
print(person.get("country"))      # None
print(person.get("country", "USA"))  # USA (default value)

Adding and Modifying

python
person = {"name": "Alice", "age": 25}

# Add new key-value
person["country"] = "USA"
print(person)  # {'name': 'Alice', 'age': 25, 'country': 'USA'}

# Update existing
person["age"] = 26
print(person)  # {'name': 'Alice', 'age': 26, 'country': 'USA'}

# Update with another dictionary
person.update({"city": "Boston", "job": "Engineer"})
print(person)
# {'name': 'Alice', 'age': 26, 'country': 'USA', 'city': 'Boston', 'job': 'Engineer'}

Removing Items

python
person = {"name": "Alice", "age": 25, "city": "New York"}

# pop() - remove and return value
city = person.pop("city")
print(city)           # New York
print(person)         # {'name': 'Alice', 'age': 25}

# popitem() - remove last item (Python 3.7+)
item = person.popitem()
print(item)           # ('age', 25)

# clear() - remove all items
person.clear()
print(person)         # {}

# del statement
person = {"name": "Alice", "age": 25}
del person["age"]
print(person)         # {'name': 'Alice'}

Dictionary Methods

python
person = {"name": "Alice", "age": 25, "city": "New York"}

# Get all keys
print(person.keys())    # dict_keys(['name', 'age', 'city'])

# Get all values
print(person.values())  # dict_values(['Alice', 25, 'New York'])

# Get all key-value pairs
print(person.items())   # dict_items([('name', 'Alice'), ('age', 25), ...])

# Iterate
for key in person:
    print(f"{key}: {person[key]}")

# Or use items()
for key, value in person.items():
    print(f"{key}: {value}")

Checking Keys

python
person = {"name": "Alice", "age": 25}

print("name" in person)       # True
print("country" in person)    # False
print("age" not in person)    # False

Practical Dictionary Examples

python
# Word counter
text = "hello world hello python world"
words = text.split()

word_count = {}
for word in words:
    if word in word_count:
        word_count[word] += 1
    else:
        word_count[word] = 1

print(word_count)
# {'hello': 2, 'world': 2, 'python': 1}

# Phone book
phonebook = {
    "Alice": "555-1234",
    "Bob": "555-5678",
    "Charlie": "555-9012"
}

# Lookup
name = "Alice"
print(f"{name}'s phone: {phonebook.get(name, 'Not found')}")

Tuples

Tuples are ordered, immutable sequences. Once created, they cannot be changed.

Creating Tuples

python
# Basic tuple
coordinates = (10, 20)
print(coordinates)    # (10, 20)

# Tuple with multiple types
mixed = (1, "hello", 3.14)
print(mixed)          # (1, 'hello', 3.14)

# Single item tuple (note the comma)
single = (42,)
print(single)         # (42,)

# Without parentheses (packing)
point = 10, 20
print(point)          # (10, 20)

# Empty tuple
empty = ()
print(empty)          # ()

Accessing Tuple Elements

python
# Indexing (like lists)
colors = ("red", "green", "blue", "yellow")

print(colors[0])      # red
print(colors[-1])     # yellow

# Slicing (like lists)
print(colors[1:3])    # ('green', 'blue')
print(colors[::2])    # ('red', 'blue')

Tuple Unpacking

python
# Unpack into variables
point = (10, 20)
x, y = point
print(f"x: {x}, y: {y}")   # x: 10, y: 20

# Swap values
a = 5
b = 10
a, b = b, a
print(f"a: {a}, b: {b}")   # a: 10, b: 5

# Unpack with *
numbers = (1, 2, 3, 4, 5)
first, *middle, last = numbers
print(first)    # 1
print(middle)   # [2, 3, 4]
print(last)     # 5

Tuple Methods

python
# count() - occurrences of value
numbers = (1, 2, 3, 2, 4, 2)
print(numbers.count(2))   # 3

# index() - first occurrence
print(numbers.index(3))   # 2

Converting Between List and Tuple

python
# List to tuple
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple)    # (1, 2, 3)

# Tuple to list
my_tuple = (1, 2, 3)
my_list = list(my_tuple)
print(my_list)     # [1, 2, 3]

Tuples vs Lists vs Dictionaries

FeatureListTupleDictionary
Orderedβœ… Yesβœ… Yesβœ… Yes (3.7+)
Mutableβœ… Yes❌ Noβœ… Yes
Indexedβœ… By positionβœ… By positionBy key
Syntax[1, 2, 3](1, 2, 3){"a": 1}
Use forCollection of itemsFixed dataKey-value pairs

When to Use What

Use Lists When:

  • You have a collection of items
  • Order matters
  • You need to add/remove items
python
fruits = ["apple", "banana", "cherry"]

Use Tuples When:

  • Data shouldn't change (coordinates, RGB values)
  • Return multiple values from a function
  • Dictionary keys (tuples are hashable)
python
coordinates = (10, 20)  # Fixed position
rgb = (255, 0, 0)       # Color values

Use Dictionaries When:

  • You need key-value associations
  • Fast lookup by key is needed
  • Data is naturally paired
python
person = {"name": "Alice", "age": 25}

Summary

In this tutorial, you learned:

  • βœ… Creating and using dictionaries
  • βœ… Accessing, adding, modifying, and removing dictionary data
  • βœ… Dictionary methods (keys, values, items)
  • βœ… Creating and using tuples
  • βœ… Tuple unpacking
  • βœ… When to use lists, tuples, or dictionaries

πŸ§‘β€πŸ’» Practice Exercise

Create a program that:

  1. Creates a dictionary with student names as keys and their scores as values
  2. Calculates and prints the average score
  3. Finds the student with the highest score
  4. Adds a new student and their score
  5. Prints all students and their scores
Click to see solution
python
# Student scores dictionary
scores = {
    "Alice": 95,
    "Bob": 82,
    "Charlie": 78,
    "Diana": 91,
    "Eve": 88
}

# Calculate average
average = sum(scores.values()) / len(scores)
print(f"Average score: {average:.2f}")

# Find highest score
highest_student = max(scores, key=scores.get)
print(f"Highest scorer: {highest_student} ({scores[highest_student]})")

# Add new student
scores["Frank"] = 76
print(f"\nAdded Frank with score {scores['Frank']}")

# Print all students
print("\n--- All Students ---")
for name, score in scores.items():
    print(f"{name}: {score}")

Output:

Average score: 86.80 Highest scorer: Alice (95) --- All Students --- Alice: 95 Bob: 82 Charlie: 78 Diana: 91 Eve: 88 Frank: 76

What's Next

In the next tutorial, we'll learn about Functions - Basics - creating reusable blocks of code.

Functions - Basics β†’

Comments (0)

No comments yet. Be the first to comment!

Leave a comment