I didn't understand when I remove list() from list_of_dictionaries , python gives this error 'dictionary changed size during iteration'
dissimilar_frag_dict=frag_dict
list_of_dictionary_elements=list(frag_dict.items()) #this is the problem
for s1_key,s1_value in list_of_dictionary_elements :
for s2_key,s2_value in list_of_dictionary_elements :
similarity=get_similarity(s1_value,s2_value)
if similarity>=threshold and s1_key!=s2_key:
max_lexicographic_order=max(s1_key,s2_key)
dissimilar_frag_dict.pop(max_lexicographic_order,'dne')
print(f'number 0f dissimilar genes:{len(dissimilar_frag_dict)}')
return dissimilar_frag_dict
CodePudding user response:
As @john-gordon has said. This line
dissimilar_frag_dict=frag_dict
actually means gives the reference of frag_dict to dissimilar_frag_dict. They both point to the same content. list(frag_dict.items()) gives a list of item dicts that is iterated. In midst of iteration you run
dissimilar_frag_dict.pop(max_lexicographic_order,'dne')
that is exactly the same as
frag_dict.pop(max_lexicographic_order,'dne')
what comes from fact that dissimilar_frag_dict references frag_dict. Thus the contents of dictionary actually changes in midst of iteration. It is not allowed, because the content taken out from the dict could be the current iterated value and the next value would be invalid in these conditions, triggering the referred error to avoid potential issues.
What I suggest you do is replace
dissimilar_frag_dict=frag_dict
by
dissimilar_frag_dict={**frag_dict}
that creates a new dictionary with the copy of key/value pairs of the old one.