Skip to content

Use Dictionary Items

Sourcery refactoring id: use-dict-items

Description:

Use dictionary.items() in for loops to access both key and value at same time

Before:

hats_by_colour = {"blue": ["panama", "baseball_cap"]}
for hat_colour in hats_by_colour:
    hats = hats_by_colour[hat_colour]
    if hat_colour in FAVOURITE_COLOURS:
        think_about_wearing(hats)

After:

hats_by_colour = {"blue": ["panama", "baseball_cap"]}
for hat_colour, hats in hats_by_colour.items():
    if hat_colour in FAVOURITE_COLOURS:
        think_about_wearing(hats)

Explanation:

When iterating over a dictionary a good tip is that you can use items() to let you access the keys and values at the same time.

This saves us the line that we used to assign to hats, incorporating it into the for loop. The code now reads more naturally, with a touch less duplication.