Iterating through dictionaries, lists, tuples, sets, and other iterable objects is a common task in Python programming. Loops allow you to execute a block of code repeatedly, making it easy to traverse, access, and manipulate the items in an iterable data structure.
This guide will demonstrate how to loop through dictionaries and other built-in Python iterable containers to access, print, filter, and transform their elements. We will cover the following topics in-depth with example code snippets:
Table of Contents
Open Table of Contents
- Overview of Built-in Iterable Containers in Python
- Basic Looping Through Dictionaries and Other Iterables
- Accessing Dictionary Keys, Values, and Key-Value Pairs
- Looping Techniques with Dictionary Methods
- Filtering and Transforming Elements
- Looping Through Nested Dictionaries and Lists
- Iterating Multiple Dictionaries and Iterables
- Useful Practices for Looping Through Iterables
- Conclusion
Overview of Built-in Iterable Containers in Python
In Python, iterable objects are containers that can return one element at a time when iterated over in a loop. The main built-in iterable data types in Python include:
- List: Ordered mutable sequence of elements.
- Tuple: Ordered immutable sequence of elements.
- Set: Unordered collection of unique elements.
- Dictionary: Unordered collection of key-value pairs.
- String: Ordered sequence of characters.
- Range: Immutable sequence of numbers.
These iterable containers can be looped through using for
loops in Python. The elements in an iterable can be accessed, printed, and manipulated one by one on each iteration of the loop.
Let’s look at some examples of built-in iterables:
# List example
numbers = [1, 2, 3, 4, 5]
# Tuple example
colors = ('red', 'green', 'blue')
# Set example
unique_vals = {3, 5, 7}
# Dictionary example
country_capitals = {'USA': 'Washington DC', 'India': 'New Delhi'}
# String example
name = 'John'
# Range example
nums = range(5)
These are common iterable data structures that we will use in the looping examples in this guide.
Basic Looping Through Dictionaries and Other Iterables
The simplest way to loop through a dictionary or other iterable in Python is to use a for
loop on the object.
Here is the basic syntax:
for element in iterable:
# Code block to execute for each element
This will iterate through each element in iterable
and execute the code block once per element.
Let’s go through examples of looping through some common iterables:
Looping Through a Dictionary
country_capitals = {'USA': 'Washington DC',
'India': 'New Delhi',
'China': 'Beijing'}
for country in country_capitals:
print(country) # Prints keys
# Output:
# USA
# India
# China
This loops through the country_capitals
dictionary and prints each key.
To access the values, we can use:
for capital in country_capitals.values():
print(capital)
# Output:
# Washington DC
# New Delhi
# Beijing
Looping Through a List
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
# Output:
# 1
# 2
# 3
# 4
# 5
This iterates through the numbers
list and prints each element.
Looping Through a Tuple
Tuples are looped through in the same way:
colors = ('red', 'green', 'blue')
for color in colors:
print(color)
# Output:
# red
# green
# blue
Looping Through a String
We can traverse through a string character by character:
name = 'John'
for char in name:
print(char)
# Output:
# J
# o
# h
# n
This accesses each character in the name
string in each iteration.
Looping Through a Range
To loop through a sequence of numbers, we can use the range()
function:
for i in range(5):
print(i)
# Output:
# 0
# 1
# 2
# 3
# 4
This will iterate from 0 up to (but not including) 5.
These examples demonstrate the basics of iterating through some common built-in Python iterables using for
loops. Next, let’s look at techniques for accessing items in a dictionary.
Accessing Dictionary Keys, Values, and Key-Value Pairs
When looping through a dictionary, we can directly access its keys and values in different ways:
Accessing Dictionary Keys
We can access the keys by looping through the dictionary:
country_capitals = {'USA': 'Washington DC', 'India': 'New Delhi'}
for country in country_capitals:
print(country)
# Output:
# USA
# India
Accessing Dictionary Values
To get the values, use the values()
method:
for capital in country_capitals.values():
print(capital)
# Output:
# Washington DC
# New Delhi
Accessing Key-Value Pairs
To access both the key and value, use the items()
method:
for country, capital in country_capitals.items():
print(f'The capital of {country} is {capital}')
# Output:
# The capital of USA is Washington DC
# The capital of India is New Delhi
This iterates through the dictionary’s (country_capitals
) items as key-value tuples, allowing us to access both the key and value conveniently.
Looping Techniques with Dictionary Methods
Dictionaries provide several methods like keys()
, values()
, and items()
that return special dictionary view objects. These objects can be looped through directly or converted to lists and tuples.
Some useful techniques:
Looping Through Dictionary View Objects
We can loop through the keys()
, values()
and items()
views directly:
country_capitals = {'USA': 'Washington DC', 'India': 'New Delhi'}
for capital in country_capitals.values():
print(capital)
for country in country_capitals.keys():
print(country)
for country, capital in country_capitals.items():
print(country, capital)
This is convenient and avoids creating separate lists.
Converting Views to Lists and Tuples
Views can be typecast to lists and tuples:
countries = list(country_capitals.keys())
capitals = tuple(country_capitals.values())
This allows accessing them as normal lists and tuples.
Sorting Dictionary Views
Views can be sorted:
for country in sorted(country_capitals.keys()):
print(country)
for capital in sorted(country_capitals.values()):
print(capital)
Sorting the views allows iterating through the items in sorted order.
Overall, leveraging dictionary views can make looping more efficient and flexible.
Filtering and Transforming Elements
We can use conditional logic inside loops to filter and transform elements in an iterable.
Filtering Elements
To filter elements, use an if
statement:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
if num % 2 == 0:
print(num)
# Output:
# 2
# 4
# 6
# 8
# 10
This iterates through numbers
and only prints even numbers by checking the condition num % 2 == 0
.
We can also filter using the filter()
function:
even_nums = filter(lambda x: x % 2 == 0, numbers)
print(list(even_nums))
# Output: [2, 4, 6, 8, 10]
The filter function takes a lambda function and iterable and returns a filter object containing only the filtered elements.
Transforming Elements
To transform elements, apply operations on them:
names = ['John', 'Mary', 'Bob', 'Sarah']
for name in names:
print(name.upper())
# Output:
# JOHN
# MARY
# BOB
# SARAH
This transforms each name to uppercase.
We can also use map()
to transform:
uppercase_names = map(str.upper, names)
print(list(uppercase_names))
# Output: ['JOHN', 'MARY', 'BOB', 'SARAH']
The map()
function applies the function str.upper to each element.
Looping Through Nested Dictionaries and Lists
For nested data structures, we can loop through the outer container and then iterate through each inner set of items.
Nested Dictionary
country_info = {
'USA': {
'Capital': 'Washington DC',
'Population': 330000000
},
'India': {
'Capital': 'New Delhi',
'Population': 1380000000
}
}
for country, info in country_info.items():
print(f'\nCountry: {country}')
for key, value in info.items():
print(f'{key}: {value}')
# Output:
# Country: USA
# Capital: Washington DC
# Population: 330000000
# Country: India
# Capital: New Delhi
# Population: 1380000000
This loops through the outer country_info
dictionary and then iterates through the inner info dictionaries.
Nested List
For nested lists, loop through the outer list and then iterate through each inner list:
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
for row in matrix:
for num in row:
print(num)
# Output:
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
This iterates through each inner list row-wise.
We can access the index on each level:
for i, row in enumerate(matrix):
for j, num in enumerate(row):
print(f'Matrix[{i}][{j}] = {num}')
This prints the 2D coordinates of each element.
Iterating Multiple Dictionaries and Iterables
When dealing with related data split across multiple dictionaries or iterables, we can loop through them simultaneously using the zip()
function.
Zipping Dictionaries
countries = ['USA', 'India', 'China']
capitals = ['Washington DC', 'New Delhi', 'Beijing']
for country, capital in zip(countries, capitals):
print(f'The capital of {country} is {capital}')
# Output:
# The capital of USA is Washington DC
# The capital of India is New Delhi
# The capital of China is Beijing
Zipping combines the elements into key-value pairs.
Zipping Lists
names = ['John', 'Mary', 'Bob']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f'{name} is {age} years old')
# Output:
# John is 25 years old
# Mary is 30 years old
# Bob is 35 years old
This iterates through two lists in parallel.
zip()
can be used to conveniently loop through data split across different iterables.
Useful Practices for Looping Through Iterables
Here are some useful tips for looping through dictionaries and iterables in Python:
-
Use plural names for iterables like
for country in countries
. Avoid single names likefor c in countries
. -
Loop directly through views instead of converting to lists when possible.
-
Use enumerate() to access the index while iterating.
-
Loop through a copy if modifying the iterable to avoid unexpected behavior.
-
Use unpacking to split elements like
for key, value in pairs.items()
. -
Prefer
for
overwhile
for iterating through iterables. -
Use
zip()
andrange()
rather than indexing to iterate multiple iterables. -
Keep loop bodies small and move complex logic outside the loop if needed.
-
Use
break
,continue
, andelse
statements for additional loop control.
Properly leveraging these practices can help write cleaner and more efficient loops in Python.
Conclusion
This guide covered a variety of techniques for looping through dictionaries, lists, sets, tuples and other built-in Python data structures. The key takeaways include:
-
Use
for
loops to iterate through dictionaries, lists, tuples, sets, strings. -
Access dictionary keys, values and items using
keys()
,values()
anditems()
. -
Leverage dictionary views and
zip()
for flexible iterations. -
Filter and transform elements using
if
statements,filter()
, andmap()
. -
Use nested loops for iterating through nested data structures.
-
Apply best practices like avoiding state changes and using plural names.
Looping is a fundamental concept in Python. Mastering iteration through dictionaries, lists, and other data structures will help in writing more robust and efficient Python code across projects.