Use Dictionary Items
Documentation Index
Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt
Use this file to discover all available pages before exploring further.
Sourcery refactoring id: use-dict-items
Section titled “Sourcery refactoring id: use-dict-items”Description:
Section titled “Description:”Use dictionary.items() in for loops to access both key and value at same
time
Before:
Section titled “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:
Section titled “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:
Section titled “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.