I am running into issues iterating through, and modifying, a dictionary...
Say I have a dictionary:
dict1 = {'A' : 'first', 'B' : 'second', 'C' : 'third', 'D' : 'fourth'}
I want to iterate through dict1, using the data within to build up a second dictionary. Once finished with each entry in dict1
, I delete it.
In pseudocode:
dict2 = {}
for an entry in dict1:
if key is A or B:
dict2[key] = dict1[key] # copy the dictionary entry
if key is C:
do this...
otherwise:
do something else...
del dict1[key]
I know that altering the length of an iterable in a loop causes problems and the above may not be simple to achieve.
The answer to this question to this question seems to indicate that I can use the keys()
function as it returns a dynamic object. I've thus tried:
for k in dict1.keys():
if k == A or k == B:
dict2[k] = dict1[k]
elif k == C:
dothis()
else:
dosomethingelse()
del dict1[k]
But, this simply gives:
'RuntimeError: dictionary changed size during iteration'
after the first deletion. I have also tried using iter(dict1.keys())
but got the same error.
I'm thus a little confused and could do with some advice. Thanks