1

This is a simple exercise that can be solved in different ways I just don't know why this does not work. I start with a dictionary, then I want to change its keys to an upper case but this throws an error ------ RuntimeError: dictionary changed size during iteration

semana = {"Lunes": 4,
           "Martes": 5,
           "Miercoles": 5,
           "Jueves": 4,
           "Viernes": 4,
           "Sabado": 4,
           "Domingo": 4}

for key, value in semana.items():
    semana[key.upper()] = value
    del semana[key]

1 Answers1

1

The problem is you're trying to change the dictionary while iterating over it. This interferes with the iteration. Instead, you need to create a new dictionary. You can do it like this:

new_dict = {}
for key, value in semana.items():
    new_dict[key.upper()] = value

You can also use a comprehension to create the new dict:

new_dict = {key.upper(): value for key, value in semana.items()}
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
  • `list(semana.items()):` should also work because `items()` returns a view, but yes, the comp is the way to go. – ggorlen Sep 09 '20 at 02:56
  • @ggorlen That would create a list of tuples using the original keys, rather than the uppercase keys. And `dict(semana.items())` would copy the dict, but again, it would use the original keys rather than the uppercase keys. – Tom Karzes Sep 09 '20 at 02:59
  • Yeah, I'm talking about keeping OP's original code and just adding `list()` around the `items()` call for the `for` loop. It's not a good solution, but it's the most minimal way to fix the problem. – ggorlen Sep 09 '20 at 03:16
  • @ggorlen Oh, got it - yes that makes sense. – Tom Karzes Sep 09 '20 at 03:23