While enumerating through a dictionary why I am getting "dictionary changed size during iteration" error?

44 views Asked by At
di=dict([(45,"Sdds"),(34,"Dffd")])
for key,di[key] in enumerate(di):
    print("we are at key "+str(key)+" and value in dict "+str(di[key]))

While running this code I am getting "RuntimeError: dictionary changed size during iteration". Can you help me how to handle this error?

2

There are 2 answers

0
Andrej Kesely On

With syntax for key,di[key] in enumerate(di): you're modifying the dictionary while iterating: first iteration the key = 0 and then you're trying to set di[0] with one of the key found already in dictionary.

Try this instead:

di = dict([(45, "Sdds"), (34, "Dffd")])

for key, item in di.items():
    print(f"we are at key {key} and value in dict {item}")

Prints:

we are at key 45 and value in dict Sdds
we are at key 34 and value in dict Dffd
0
Suramuthu R On

The purpose of using enumerate in iterating over dictionary is: With this method, we can get the index of each item as well. If you want to use enumerate, your code should be as follows:

di=dict([[45,"Sdds"],[34,"Dffd"]])

for x in enumerate(di):
    key = x[1]
    print("we are at key "+str(key)+" and value in dict "+str(di[key]))

'''
output:
we are at key 45 and value in dict Sdds
we are at key 34 and value in dict Dffd
'''

As long as you don't want to know the index of the item in dictionary, you don't need to use enumerate. the enumerate method has three following syntax:

dct = {'key_1':'value_1','key_2':'value_2','key_3':'value_3'}

#iterate over keys with enumerate
for x in enumerate(dct):
    print(x)

'''
Output:
(0, 'key_1')
(1, 'key_2')
(2, 'key_3')
'''

#iterate over values with enumerate
for x in enumerate(dct.values()):
    print(x)

'''
output:
(0, 'value_1')
(1, 'value_2')
(2, 'value_3')
'''

#iterate over items with enumerate
for x in enumerate(dct.items()):
    print(x)

'''
output:
(0, ('key_1', 'value_1'))
(1, ('key_2', 'value_2'))
(2, ('key_3', 'value_3'))
'''

In all the above examples 0,1, and 2 are index of the items. If at all you need to use these index in your program later, them you can use enumerate method. If index is not required, then normal iteration will do.