5 Ways to Loop a Dictionary in Python


Dictionaries are the most used data structure in Python and one has to often loop through it.

In this article, we take a look at 5 ways to loop a dictionary.


Example 1: Loop Through Dict Keys

    week_numbers = {1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday'}
    
    for week_number in week_numbers:
        print(week_number)
    
    Output:
    1
    2
    3
    4
    5

Example 2: Loop Through Dict Values

    week_names = {1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday'}
    
    for week_name in week_names.values():
        print(week_name)

    Output:
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday

Example 3: Loop Through Dict Key-Value Pairs

    week_days = {1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday'}
    
    for week_number, week_name in week_days.items():
        print(f"Week {week_number}: {week_name}")

    Output:
    Week 1: Monday
    Week 2: Tuesday
    Week 3: Wednesday
    Week 4: Thursday
    Week 5: Friday

Example 4: Loop Through Sorted Keys

    week_numbers = {5: 'Friday', 3: 'Wednesday', 1: 'Monday', 4: 'Thursday', 2: 'Tuesday'}
    
    for week_number in sorted(week_numbers):
        print(week_number)
    

    Output:
    1
    2
    3
    4
    5

Example 5: Loop Through Keys and Indexes

    week_names = {1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday'}
    
    for index, week_number in enumerate(week_names, start=1):
        print(f"Week {week_number} (Index: {index}): {week_names[week_number]}")
    Output:
    Week 1 (Index: 1): Monday
    Week 2 (Index: 2): Tuesday
    Week 3 (Index: 3): Wednesday
    Week 4 (Index: 4): Thursday
    Week 5 (Index: 5): Friday

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap