How do I update values in a nested dictionary in python without getting error "dictionary changed size during iteration"?

Question:

Python beginner here. The project I’m working on uses a nested dictionary of different business locations and their hours by day of week. It’s formatted like this:

all_branch_hours = {
    'Branch 1': {
            'Sunday': '12:00-18:00',
            'Monday': '09:00-18:00',
            'Tuesday': '09:00-20:00',
            'Wednesday': '09:00-20:00',
            'Thursday': '09:00-20:00',
            'Friday': '12:00-18:00',
            'Saturday': '10:00-18:00'
    },
    'Branch 2': {
            'Sunday': '13:00-17:00',
            'Monday': '10:00-18:00',
            'Tuesday': '10:00-20:00',
            'Wednesday': '13:00-20:00',
            'Thursday': '10:00-18:00',
            'Friday': '13:00-18:00',
            'Saturday': '10:00-18:00'
    },
    'Branch 3': {
            'Sunday': '13:00-17:00',
            'Monday': '10:00-18:00',
            'Tuesday': '10:00-20:00',
            'Wednesday': '10:00-20:00',
            'Thursday': '10:00-20:00',
            'Friday': '13:00-18:00',
            'Saturday': '10:00-18:00'
    }
}

I want to generate a new dictionary where the hours are converted to lists of integers so that I can run a script later that checks whether or not a time is within open hours. For example the string "12:00-18:00" would become list [12,13,14,15,16,17].

Here’s what I tried:

import copy
datetime_branch_hours = copy.deepcopy(all_branch_hours)

for key, value in datetime_branch_hours.items():
        for k in value.values():
             openhour= int(k[0:2])
             closehour= int(k[6:8])
             open_hour_range = list(range(openhour, closehour))
             value[k] = open_hour_range`

I’ve tried this which I though should work, but I keep getting "RuntimeError: dictionary changed size during iteration". I know that editing a copy can avoid this error, but I don’t know how to do that with a nested dictionary. Any help would be greatly appreciated!

Asked By: Graham Galloway

||

Answers:

You are using wrong key for the inner dictionaries, causing addition of new keys while iterating. You need to iterate over the items of the inner dictionaries to get access to their true keys.

for key, value in all_branch_hours.items():
        for k, v in value.items():  # now k is truly key of inner dictionaries
            openhour= int(v[0:2])
            closehour= int(v[6:8])
            open_hour_range = list(range(openhour, closehour))
            value[k] = open_hour_range
Answered By: bui
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.