I want to define a generator function that can iterate through a dictionary object that is mutating.
def generator(d):
for k,v in sorted(d.items()):
yield (k,v)
d = {1:'a', 2:'x', 4:'m', 8:'d', 16:'f'}
i = generator(d)
print(next(i))
print(next(i))
del d[8]
print(next(i))
d[16] = "f"
d[32] = "z"
print(next(i))
print(next(i))
If I execute the code above, I will get:
(1, 'a')
(2, 'x')
(4, 'm')
(8, 'd')
(16, 'f')
The desired output should be:
(1, 'a')
(2, 'x')
(4, 'm')
(16, 'f')
(32, 'z')
The part I don't understand is when I assign d = {1:'a', 2:'x', 4:'m', 8:'d', 16:'f'} to i = generator(d) The dictionary is already added into function generator(d) and becomes a generator instance with the initial dictionary. So whenever I use del function, the generator stays unchanged with d = {1:'a', 2:'x', 4:'m', 8:'d', 16:'f'} as its parameter. How am I gonna achieve this?