Reputation: 609
I have some code I'm analyzing. But I've found that iterating over a dictionary empties it. I've fixed the problem by by making a deepcopy of the dictionary and iterating over that in some code that displays the values, then later use the original dictionary to iterate over that to assign values to a 2D array. Why does iterating over the original dictionary to display it empty it, so that later use of the dictionary is unusable since it is now empty? Any replies welcome.
import copy
# This line fixed the problem
trans = copy.deepcopy(transitions)
print ("\nTransistions = ")
# Original line was:
# for state, next_states in transitions.items():
# Which empties the dictionary, so not usable after that
for state, next_states in trans.items():
for i in next_states:
print("\nstate = ", state, " next_state = ", i)
# Later code which with original for loop showed empty dictionary
for state, next_states in transitions.items():
for next_state in next_states:
print("\n one_step trans state = ", state, " next_state = ", next_state)
one_step[state,next_state] += 1
A print of the dictionary:
Transistions =
{0: <map object at 0x0000000003391550>, 1: <map object at 0x00000000033911D0>, 2: <map object at 0x0000000003391400>, 3: <map object at 0x00000000033915F8>, 4: <map object at 0x0000000003391320>}
Type:
Transistions =
<class 'dict'>
Edit: Here's the code that uses map. Any suggestions on how to edit it to created the dictionary without using map?
numbers = dict((state_set, n) for n, state_set in enumerate(sets))
transitions = {}
for state_set, next_sets in state_set_transitions.items():
dstate = numbers[state_set]
transitions[dstate] = map(numbers.get, next_sets)
Upvotes: 0
Views: 70
Reputation: 281252
Iterating over a dict doesn't empty it. Iterating over a map iterator empties it.
Wherever you generated your transitions
dict, you should have used a list comprehension instead of map
to create lists instead of iterators for the values:
[whatever for x in thing]
instead of
map(lambda x: whatever, thing)
Upvotes: 1