python dictionary problem
output of n is in the form:- ((6,5),'north',1)
I am making a dict child for it...in which (6,5)
is the key and north
and 1
are the values. I need to keep the (6,5)
as the key and north
as a direction...开发者_如何学Python.and I want to keep adding all the values till the while
loop continues
If you want to keep all the key / value pairs in one dict (and all keys are distinct, of course):
totaldict = {}
for ...whatever your loop is...:
...
totaldict.update(( t[0], t[1:]) for t in n )
If you want a list of dicts, @San's answer is good. If you want a single dict with not necessarily all distinct keys, and each key's corresponding value a list of tuples:
import collections
totaldict = collections.defaultdict(list)
for ...whatever your loop is...:
...
for t in n:
totaldict[t[0]].append(t[1:])
There may be other senses yet which you might mean "keep all the values of this dictioanary" to signify, but it is, as usual, impossible to guess precisely in what of the many possible meanings you intend it.
Edit: from the OP's edit (much-clarifying his question, though many murky aspects remain which I already asked about on some of his previous questions), he doesn't necessarily need one dict -- he needs to be able to trace any path backwards when he finally gets to a node that's deemed by the problem object to be "a solution" (or "goal").
The OP's edit to the Q now seems to mysteriously have disappeared, but if (as I dimly recall) he's skipping any node that's previously been pushed onto the stack, then one dict will do, because each node will be visited at most once (hence, no duplicate keys) -- however, that dict's entry, with the node as a key, should not point to the node's successors (signally useless in tracing the path backwards from the goal!), but to the predecessor which led to visiting this node (and the direction that was taken from that immediate predecessor to come to this node). The root's node entry should be empty (since it has no predecessor).
It sounds like you want a list of dictionaries, but it's difficult to tell with so little context.
my_list = []
while some_loop_condition:
child = dict(( t[0], t[1:]) for t in n )
my_list.append(child)
It looks like you want to define 'child' outside if the loop, and reference it within:
e.g.:
child = {}
while blah:
...
child.update(dict(( t[0], t[1:]) for t in n )
...
精彩评论