tags:

views:

56

answers:

3

I have made a dictionary and I put the keys of the dict in a list. My list contains elements like this:

s =  [((5, 4), 'South', 1), ((4, 5), 'West', 1)]

I made a dict from this:

child = dict((t[0], t[1]) for t in s)

keys = child.keys()
print keys

The output is : [(4, 5), (5, 4)]

Now I need to put (4,5) and (5,4) into stack. What should I do?

I tried, but when I do pop from the stack it is giving me the 2 elements together. like stack.pop() - output is : [(4, 5), (5, 4)]. I want to pop one by one... (4,5) and then (5,4)

A: 

use

element = stack[0]
if len(stack) > 0:
   stack = stack[1:]

print element

but it is not that kind of a stack :/

Quonux
i need the soln for proper stack....I hav to use pop n push
Shilpa
@shilpa, pushing and popping on a list *is* a proper stack. push puts on the end, pop removes from the end.
eruciform
it is basicaly the same, you can "wrap" this in a own class and call it stack (with your function names and so on)
Quonux
A: 

I think user wants this:

# python
> stack = [(4, 5), (5, 4)]
> stack.pop(0)
(4,5)
> stack.pop(0)
(5,4)

Just a reminder, though, this is not a proper stack. This is a proper stack:

# python
> stack=[]
> stack.append( (4,5) )    
> stack.append( (5,4) )
> stack.pop()
(5,4)
> stack.pop()
(4,5)
eruciform
hey, i wrote the same...
Quonux
+2  A: 

You can use a list as a stack:

stack = list(child.keys())
print stack.pop()
print stack.pop()

Result:

(5, 4)
(4, 5)

Important note: the keys of a dictionary are not ordered so if you want the items in a specific order you need to handle that yourself. For example if you want them in normal sorted order you could use sorted. If you want them to pop off in reverse order from the order they were in s you could skip the conversion to a dictionary and just go straight from s to your stack:

stack = [x[0] for x in s]
print stack.pop()
print stack.pop()

Result:

(4, 5)
(5, 4)
Mark Byers
+1 for mentioning that dictionary keys are not ordered.
Felix Kling