Back to: Python for Medical Imaging
Organizing Medical Imaging Information in Python
Difficulty: Beginner
Reading Time: 25–30 minutes
Prerequisites:
- Completed Module 1: Getting Started
- Understanding of variables and data types
- Basic understanding of
print()
Learning Objectives
After completing this lesson, you will be able to:
- Understand what lists and dictionaries are.
- Create and modify Python lists.
- Access individual elements in a list.
- Loop through lists.
- Create and work with dictionaries.
- Access information using dictionary keys.
- Add, modify, and remove dictionary information.
- Combine lists and dictionaries.
- Apply lists and dictionaries to medical imaging examples.
- Understand when to use a list versus a dictionary.
Introduction
Medical imaging involves working with large amounts of organized information.
A CT examination may contain:
- Hundreds or thousands of images
- Multiple series
- Patient information
- Scanner information
- Acquisition parameters
- Pixel spacing
- Slice thickness
- Image dimensions
Storing each piece of information in a separate variable can quickly become difficult to manage.
For example:
slice_1 = 1
slice_2 = 2
slice_3 = 3
slice_4 = 4
Imagine doing this for 500 CT slices.
There is a much better solution.
Python provides data structures such as lists and dictionaries that allow us to organize related information efficiently.
Part 1 — Lists
What is a List?
A list is a collection of values stored together in a specific order.
Example:
modalities = ["CT", "MRI", "X-ray", "PET"]
After completing this lesson, you will be able to:
Creating a List
Lists are created using square brackets [].
slice_thicknesses = [0.5, 0.625, 1.0, 1.25]
We can print the entire list:
print(slice_thicknesses)
Output:
[0.5, 0.625, 1.0, 1.25]
Accessing List Elements
Python uses index numbers to access individual elements.
Important:
Python indexing starts at 0, not 1.
For example:
modalities = ["CT", "MRI", "X-ray", "PET"]
The indexes are:
CT → 0
MRI → 1
X-ray → 2
PET → 3
Therefore:
print(modalities[0])
Output:
CT
And:
print(modalities[2])
Output:
X-ray
Medical Imaging Example
Suppose a CT examination contains several series:
series = [
"Scout",
"Non-contrast CT",
"Arterial phase",
"Venous phase"
]
We can access an individual series:
print(series[1])
Output:
Non-contrast CT
Negative Indexing
Python also allows negative indexes.
modalities = ["CT", "MRI", "X-ray", "PET"]
The last element can be accessed using:
print(modalities[-1])
Output:
PET
The second-to-last element:
print(modalities[-2])
Output:
X-ray
This is particularly useful when working with datasets where you may want to access the last image, last slice, or last item
Changing List Elements
Lists are mutable, which means their contents can be changed.
modalities = ["CT", "MRI", "X-ray"]
We can access an individual series:
Suppose we want to change "X-ray" to "PET":
modalities[2] = "PET"
Now:
print(modalities)
Output:
['CT', 'MRI', 'PET']
Adding Items to a List
Use append() to add an item to the end of a list.
modalities = ["CT", "MRI"]
modalities.append("PET")
print(modalities)
Output:
['CT', 'MRI', 'PET']
Adding Multiple Items
You can also add several items using extend().
modalities = ["CT", "MRI"]
modalities.extend(["PET", "X-ray"])
print(modalities)
Output:
['CT', 'MRI', 'PET', 'X-ray']
Removing Items
Use remove() to remove an item.
modalities = ["CT", "MRI", "PET"]
modalities.remove("MRI")
print(modalities)
Output:
['CT', 'PET']
You can also use pop() to remove an item using its index.
modalities.pop(1)
Finding the Length of a List
The len() function tells us how many elements are in a list.
ct_slices = [1, 2, 3, 4, 5]
print(len(ct_slices))
Output:
5
In real medical imaging applications, this concept becomes very useful.
For example:
number_of_slices = len(ct_slices)
Looping Through a List
One of the most important uses of lists is processing multiple items.
modalities = ["CT", "MRI", "X-ray", "PET"]
for modality in modalities:
print(modality)
Output:
CT
MRI
X-ray
PET
This is extremely important in medical imaging.
Imagine having:
500 CT slices
Instead of writing 500 commands, we can process them using a loop.
for slice_number in ct_slices:
print(slice_number)
Later in PyMedLab, the same concept will allow us to process:
DICOM image 1
DICOM image 2
DICOM image 3
...
DICOM image 500
automatically.
Sorting a List
Python can sort lists.
slice_thicknesses = [1.25, 0.5, 2.0, 0.625]
slice_thicknesses.sort()
print(slice_thicknesses)
Output:
[0.5, 0.625, 1.25, 2.0]
This can be useful when organizing image acquisition parameters or numerical measurements.
Part 2 — Dictionaries
What is a Dictionary?
A dictionary stores information as key-value pairs.
Think of it as a labeled information card.
For example:
patient = {
"name": "Sarah",
"age": 54,
"modality": "CT",
"slice_thickness": 0.625
}
Here:
Key Value
-------------------------
name Sarah
age 54
modality CT
slice_thickness 0.625
The key tells Python what the information represents.
Why Dictionaries Are Useful in Medical Imaging
Medical imaging data often contains information with different meanings.
For example:
Patient name
Age
Modality
Study date
Slice thickness
Pixel spacing
Number of images
Contrast
A dictionary is ideal for this type of information.
ct_examination = {
"patient": "Sarah",
"modality": "CT",
"slice_thickness": 0.625,
"number_of_slices": 450,
"contrast_used": True
}
Now all of the examination information is stored in one object.
Accessing Dictionary Values
Use the key:
print(ct_examination["patient"])
Output:
Sarah
Another example:
print(ct_examination["slice_thickness"])
Output:
0.625
Adding Information
We can add a new key-value pair.
ct_examination["scanner"] = "Siemens SOMATOM"
Now the dictionary contains scanner information.
Changing Information
We can modify an existing value.
ct_examination["slice_thickness"] = 1.0
The value has now changed from 0.625 to 1.0.
Removing Information
We can use del:
del ct_examination["contrast_used"]
Or:
ct_examination.pop("contrast_used")
Checking Whether a Key Exists
You can check whether a dictionary contains a particular key.
if "modality" in ct_examination:
print("Modality information is available.")
Output:
Modality information is available.
This becomes very useful when working with medical imaging metadata because not every dataset contains exactly the same information.
Looping Through a Dictionary
We can loop through the keys and values.
for key, value in ct_examination.items():
print(key, ":", value)
Output:
patient : Sarah
modality : CT
slice_thickness : 0.625
number_of_slices : 450
contrast_used : True
This is a very useful technique for displaying metadata.
Lists and Dictionaries Together
This is where Python becomes particularly powerful.
Imagine that we have information about three CT examinations.
We can create a list containing dictionaries:
ct_examinations = [
{
"patient": "Sarah",
"slice_thickness": 0.625,
"slices": 450
},
{
"patient": "John",
"slice_thickness": 1.0,
"slices": 320
},
{
"patient": "Emma",
"slice_thickness": 0.5,
"slices": 600
}
]
Now we have:
List
│
├── Dictionary → Sarah
├── Dictionary → John
└── Dictionary → Emma
This structure is very common when working with collections of medical records, image studies, or metadata.
Accessing Nested Information
We can access Sarah’s information:
print(ct_examinations[0]["patient"])
Output:
Sarah
Sarah’s slice thickness:
print(ct_examinations[0]["slice_thickness"])
Output:
0.625
Processing Multiple Examinations
We can use a loop:
for examination in ct_examinations:
print("Patient:", examination["patient"])
print("Slice Thickness:", examination["slice_thickness"])
print("Number of Slices:", examination["slices"])
print()
Output:
Patient: Sarah
Slice Thickness: 0.625
Number of Slices: 450
Patient: John
Slice Thickness: 1.0
Number of Slices: 320
Patient: Emma
Slice Thickness: 0.5
Number of Slices: 600
This is much more scalable than creating separate variables for every examination.
Lists vs Dictionaries
A simple way to remember the difference is:
List
Use a list when you have a collection of similar items.
modalities = ["CT", "MRI", "PET"]
Think:
A list of things
Dictionary
Use a dictionary when you have information describing something.
patient = {
"name": "Sarah",
"age": 54,
"modality": "CT"
}
Think:
Information about something
Practical PyMedLab Example
Let’s create a small CT examination database.
ct_studies = [
{
"patient": "Sarah",
"modality": "CT",
"slice_thickness": 0.625,
"number_of_slices": 450
},
{
"patient": "John",
"modality": "CT",
"slice_thickness": 1.0,
"number_of_slices": 320
}
]
We can process all studies:
for study in ct_studies:
print("Patient:", study["patient"])
print("Modality:", study["modality"])
print("Slice Thickness:", study["slice_thickness"], "mm")
print("Number of Slices:", study["number_of_slices"])
print("------------------------")
This example introduces an important programming concept:
Data structures allow us to organize information so that our programs can process it efficiently.
Later, PyMedLab will move from these simple examples to real DICOM datasets.
Mini Project: Medical Imaging Study Organizer
Create a program that stores information about several imaging studies.
studies = [
{
"patient": "Alice",
"modality": "CT",
"body_region": "Chest",
"images": 350
},
{
"patient": "David",
"modality": "MRI",
"body_region": "Brain",
"images": 180
},
{
"patient": "Emma",
"modality": "CT",
"body_region": "Abdomen",
"images": 500
}
]
Your program should display:
Patient: Alice
Modality: CT
Body Region: Chest
Images: 350
for each study.
Challenge
Modify the program so that it displays only CT examinations.
Hint:
if study["modality"] == "CT":
Common Beginner Mistakes
Mistake 1 — Forgetting that indexing starts at 0
❌
modalities[1]
thinking this means the first element.
✔
modalities[0]
Mistake 2 — Using the wrong dictionary key
❌
study["patient_name"]
when the dictionary contains:
"patient"
✔
study["patient"]
Dictionary keys must match exactly.
Mistake 3 — Confusing [] and {}
List:
modalities = ["CT", "MRI", "PET"]
Dictionary:
study = {
"modality": "CT",
"images": 450
}
Mistake 4 — Mixing up a list and a dictionary
A list:
modalities[0]
A dictionary:
study["modality"]
Best Practices
✔ Give lists descriptive names.
ct_slices
is better than:
x
✔ Give dictionary keys clear names.
"slice_thickness"
is better than:
"st"
✔ Use snake_case.
✔ Keep related information together.
✔ Use lists for collections.
✔ Use dictionaries for labeled information.
✔ Avoid unnecessarily complicated nested structures when a simpler structure is sufficient.
Exercises
Exercise 1 — Create a List
Create a list containing:
- CT
- MRI
- X-ray
- PET
- Ultrasound
Print the list.
Exercise 2 — Access Elements
Using your list:
- Print the first modality.
- Print the third modality.
- Print the last modality.
Exercise 3 — Modify a List
Change "X-ray" to "Mammography".
Print the updated list.
Exercise 4 — Create a Dictionary
Create a dictionary called:
patient
containing:
- name
- age
- modality
- body region
Print each value.
Exercise 5 — Medical Imaging
Create a dictionary called:
ct_scan
containing:
patient
scanner
slice_thickness
number_of_slices
pixel_spacing
contrast_used
Display the information in a readable format.
Exercise 6 — Lists + Dictionaries
Create a list containing three medical imaging studies.
Each study should contain:
- patient
- modality
- body region
- number of images
Loop through the list and display each study.
Exercise 7 — Challenge
Modify your program so that it displays only studies where:
modality == "CT"
Summary
In this lesson, you learned:
- What lists are.
- How to create and modify lists.
- How Python indexes list elements.
- How to loop through lists.
- What dictionaries are.
- How dictionaries store key-value pairs.
- How to add, modify, and remove dictionary information.
- How lists and dictionaries can be combined.
- How these structures can represent medical imaging information.
Lists and dictionaries are fundamental Python data structures.
As you continue through PyMedLab, you will see them everywhere—from simple programs to DICOM metadata, imaging datasets, machine-learning data, and research projects.
What’s Next?
In the next lessons, you will begin working with more powerful Python concepts that allow you to organize and reuse your code.
You will learn how to work with:
- Modules
- Packages
- Files
- Errors and exceptions
- Classes and objects
These concepts will prepare you for scientific Python libraries such as NumPy, Pandas, Matplotlib, and pydicom, and eventually for real medical imaging projects.

Leave a Reply