Skip to main content

Command Palette

Search for a command to run...

Dictionary size cant be changed during iteration

Published
1 min readView as Markdown
X

"I am currently a Software Engineering student at ALX. I'm passionate about technology and enjoy conducting research to find answers on my own. I have a natural inclination to ask 'WHY' more often than 'HOW'.

"While working on projects at ALX, I have acquired a wealth of interesting and diverse knowledge about software engineering and computer science in general. Therefore, I needed a place to store and save all this information, allowing me to refer back to it whenever I forget."

#!/usr/bin/python3
def complex_delete(a_dictionary, value):
    for k, v in a_dictionary.items():
        if v == value:
            del a_dictionary[k]
    return a_dictionary

When you run something like this(the code above), you will get the following errors

Traceback (most recent call last):
  File "./102-main.py", line 7, in <module>
    new_dict = complex_delete(a_dictionary, 'C')
  File "/root/alx-higher_level_programming/0x04-python-more_data_structures/102-complex_delete.py", line 3, in complex_delete
    for k, v in a_dictionary.items():
RuntimeError: dictionary changed size during iteration

why?
The issue here lies in modifying the dictionary (a_dictionary) while iterating over its items. Modifying the dictionary size during iteration can lead to unexpected results or runtime errors. To overcome this, you can create a separate list of keys to delete and then delete them after the iteration is complete. Here's an updated version below:

python
Copy code
def complex_delete(a_dictionary, value):
    keys_to_delete = []
    for k, v in a_dictionary.items():
        if v == value:
            keys_to_delete.append(k)
    for k in keys_to_delete:
        del a_dictionary[k]
    return a_dictionary

0x04. Python - More Data Structures: Set, Dictionary
102-complex_delete.py

More from this blog

PERSONAL BLOG

110 posts

Use the search button to search for a specific topic or keyword *all posts are updated on the go*