This error usually occurs when you are trying to modify a dictionary while iterating over it. When you modify the dictionary, it changes the size and the order of the keys, which makes it difficult for Python to keep track of the iteration.
Scenario 1:
This error caused in various old packages and one of popular package “JIRA”
RuntimeError: dictionary keys changed during iteration.
This error occurs while uploading attachment to jira ticket using python api.
with open(file_path, 'rb') as f:
file_contents = f.read()
# File name for the attachment
file_name = os.path.basename(file_path)
# Create the attachment object
attachment = {'name': file_name, 'data': file_contents}
# Issue key for which the attachment needs to be added
issue_key = 'YOUR-PROJECT-KEY-123'
# Add the attachment to the issue
jira.add_attachment(issue=issue_key, attachment=attachment)
Python Jira causing runtime error while attaching file using add_attachment – “dictionary keys changed during iteration”.
This error is removed in Jira 3.0 api, please update your jira package using PIP.
Steps:
pip uninstall jira
pip install jira
Scenario 2:
# Initialize a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Iterate over the keys and remove some items
for key in my_dict:
if key == 'a' or key == 'b':
del my_dict[key]
In the above example, we are trying to delete items from the dictionary while iterating over it. This will result in a “RuntimeError: dictionary keys changed during iteration” error because the size and order of the keys in the dictionary change as we delete items.
To avoid this error, you can make a copy of the dictionary and iterate over the copy while modifying the original dictionary, like this:
# Initialize a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Make a copy of the dictionary
copy_dict = my_dict.copy()
# Iterate over the keys in the copy and remove items from the original
for key in copy_dict:
if key == 'a' or key == 'b':
del my_dict[key]
In the above example, we first make a copy of the dictionary and then iterate over the copy while modifying the original. This will avoid the “RuntimeError: dictionary keys changed during iteration” error.
Thank you! Let us know if there is any question.