Looping Through Dictionaries
Part of the Logic & Flow section of Coddy's Python journey — lesson 15 of 78.
Looping through a dictionary allows you to access each key-value pair and perform operations on them. Python provides several ways to iterate through dictionaries, making it easy to work with their contents.
Looping through keys:
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
for key in my_dict:
print(key)Output:
name
age
cityLooping through values:
for value in my_dict.values():
print(value)Output:
Alice
30
New YorkLooping through key-value pairs:
for key, value in my_dict.items():
print(f'{key}: {value}')Output:
name: Alice
age: 30
city: New YorkIn these examples, the first loop iterates over the keys of the dictionary. The second loop iterates over the values using the values() method. The third loop uses the items() method to iterate over both keys and values simultaneously.
Challenge
EasyCreate a function named print_employee_details that takes a dictionary employee_data as an argument. The function should loop through the dictionary and print each key-value pair in the format 'key: value'. If the dictionary is empty, the function should print 'No data available'.
For example, we have a dictionary called employee_data:
employee_data = {"name": "John", "age": 30, "department": "Sales"}
Function output:
name: John
age: 30
department: Sales
Cheat sheet
Loop through dictionary keys:
for key in my_dict:
print(key)Loop through dictionary values using values():
for value in my_dict.values():
print(value)Loop through key-value pairs using items():
for key, value in my_dict.items():
print(f'{key}: {value}')Try it yourself
def print_employee_details(employee_data):
# Write code hereThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Variables Exploration
ConstantsMultiple Variable AssignmentsSwapping VariablesPlaceholder VariablesRound NumbersList Casting4Contact Book Application
Display MenuAdd Contact7Sets Part 2
Mathematical Operations Part 1Mathematical Operations Part 2Recap - Treasure HuntSubsets and SupersetsIterating Over SetsRecap - Tournament Tracker2Dictionaries Part 1
What is a Dictionary?Creating a DictionaryAccessing ValuesModifying DictionariesRecap - Recipe Manager5Advanced Decision Making
Ternary OperatorMembership ChecksIdentity ChecksIndentation ErrorsRecap - Vacation Filter8Student Records Manager
Project OverviewAdd Student11Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap Challenge - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested List14Higher-Order Functions
The Map FunctionThe Filter FunctionRecap - Email ValidatorRecap - Number Processor3Dictionaries Part 2
Dictionary MethodsNested DictionariesChecking for KeysLooping Through DictionariesRecap - Frequency Counter9Advanced Data Aggregation
Using SumFinding Minimum and MaximumSorting Data EfficientlyRecap - Dictionary Sorter