I am using a dictionary to save possible trajectories in a game. A trajectory is defined as a list of numbers separated by _
. For example '3_7_2_5'
is a trajectory of 4 steps. I use a dictionary as I assign a value to each trajectory. The meaning of this value does not matter for the purpose of my question. I also save the trajectories in separated dictionaries if they have different numbers of steps.
I want to update the dictionary in such a way that only the trajectories starting from '1'
are preserved. Moreover, I want to remove the '1'
from the name, since I don't need to keep listing a step that has already been made.
# here I create the initial dictionaries
pts=[{},{},{}]
for j in range(20):
k=random.choice(range(3))
path=str(k)
for d in range(len(pts)):
k=random.choice(range(4))
pts[d][path]=k
path+='_'+str(k)
print 'initial dictionaries =',pts
# here I make the update
ind=1
new_pts=[{},{},{}]
path=str(ind)
for d in range(len(pts)-1):
for path in pts[d+1]:
if path[:len(str(ind))]==str(ind):
new_pts[d][path[len(str(ind))+1:]]=pts[d+1][path]
pts=new_pts
print 'updated dictionaries =',pts
As you can see, the first element of the old list pts
has been discarded. The second element has been used to create the first element of the updated list and so on.
Now, it seems to me that my algorithm is not very efficient. For updating the dictionary I am using a for
loop over all keys, even though most of them are going to be discarded.
Is there a better, faster way to do this?
random.choice()
works by just cut&paste. Please tag python-2.x (or add parentheses to theprint
).)For [update I] loop over all keys, even though most [are] discarded
For really helpful reviews, please provide more context: Why are those entries in the dictionary in the first place? What is special about trajectories starting from '1'? (What about those starting from0
?) \$\endgroup\$'1'
.Therefore the trajectories must be updated, keeping only those that were starting by'1'
. The choice of1
specifically is arbitrary, I could have chosen0
or any number in my example. \$\endgroup\$