2

I'd like to be able to go over a dictionary, calling a function for each entry, while this function might add more entries to the same dictionary. Is it possible to have some sort of iterating method that will allow me to do this AND have the function iterate over the newly added entries at the same for loop? in example: I have dict = {"A": 1, "B": 2, "C": 3} I want to iterate over it with function f. Even if calling f(dict["A"]) puts a new entry in the dictionary, making it: {"A": 1, "B":2, "C": 3, "new key": "new value"}, I want the loop to also call f(dict["new key"]) at the same iteration.

  • Welcome to SO! Please edit your question and use the code markup button on top. – Jan Apr 12 '17 at 13:55

1 Answers1

1

You could create a deque from the keys in the dictionary, iterate over the queue and add to both, the dictionary and the queue:

import collections

dic = {"A": 1, "B": 2, "C": 3}
deq = collections.deque(dic)

while deq:
    x = deq.pop()
    print(x)
    if x == "B":
        dic["D"] = 4
        deq.append("D")
tobias_k
  • 81,265
  • 12
  • 120
  • 179