1

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)

6
  • could you clarify? what are you doing, what is it doing that you think is wrong, and what would you like it to do? Commented Jul 17, 2010 at 22:35
  • Where/What is the stack? Commented Jul 17, 2010 at 22:40
  • plz see the question again...i have made changes Commented Jul 17, 2010 at 22:41
  • 2
    i don't get it. [(4,5),(5,4)].pop() returns (5,4) ... Commented Jul 17, 2010 at 22:42
  • 3
    This question needs a lot of clarification. I wish that SO had a template for asking questions, with sections like "What I tried" and "What it should look like". Commented Jul 17, 2010 at 22:52

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

0

use

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

print element

but it is not that kind of a stack :/

2 Comments

@shilpa, pushing and popping on a list is a proper stack. push puts on the end, pop removes from the end.
it is basicaly the same, you can "wrap" this in a own class and call it stack (with your function names and so on)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.