2uzhan.com
Advertisement
Now Place:2uzhan.com » Ordered Dictionaries?

Ordered Dictionaries?

Software Development @ November 7, 2008   Views:0

I am creating a tetris-like game. I have decided to use coordinates (x,y) along with a dictionary. Here is a part of the dictionary:

gameTable = {(-5,10):0,(-4,10):0,(-3,10):0,(-2,10):0,(-1,10):0,(0,10):0, (1,10):0, (2,10):0, (3,10):0, (4,10):0, (5,10):0, (-5,9):0, (-4,9):0, (-3,9):0, (-2,9):0, (-1,9):0, (0,9):0, (1,9):0, (2,9):0, (3,9):0, (4,9):0, (5,9):0, (-5,8):0, (-4,8):0, (-3,8):0, (-2,8):0, (-1,8):0, (0,8):0, (1,8):0, (2,8):0, (3,8):0, (4,8):0, (5,8):0...

Notice that they are in proper order.
Now, take a look at what happens when I try to print it:

{(4, -3): 0, (-4, -6): 0, (-1, 0): 0, (-5, 1): 0, (3, -10): 0, (-4, 10): 0, (-5, 3): 0, (0, 4): 0, (-5, -3): 0, (1, 1): 0, (4, 10): 0, (3, 2): 0, (2, 6): 0, (-3, -8): 0, (-4, -3): 0, (-1, -2): 0, (-2, -1): 0, (-4, 4): 0, (2, -10): 0, (2, -7): 0, (-4, -7): 0, (-5, 6): 0, (-1, 3): 0...

It gets out of order.
My main question is:
How do I stop python from ordering this dictionary, if it even is?

Thanks!

--------------Solutions-------------

You have no choice when it comes to ordering dictionaries. If you want it to print nicely then you CAN order gameTable.keys() . Here is how i would do it:

gameTable = {(-5,10):0,(-4,10):0,(-3,10):0,(-2,10):0,(-1,10):0,(0,10):0, (1,10):0, (2,10):0, (3,10):0, (4,10):0, (5,10):0, (-5,9):0, (-4,9):0, (-3,9):0, (-2,9):0, (-1,9):0, (0,9):0, (1,9):0, (2,9):0, (3,9):0, (4,9):0, (5,9):0, (-5,8):0, (-4,8):0, (-3,8):0, (-2,8):0, (-1,8):0, (0,8):0, (1,8):0, (2,8):0, (3,8):0, (4,8):0}
keys = gameTable.keys()
keys.sort()
for key in keys:
    print key
    print gameTable[key]

Hope that helps.

There is an ordered dictionary module that can be found here. Works just like a regular dictionary but is kept in order.

HTH

sort() did sort out the dict, but not in the correct order.
So unfortunately, I am forced to use a list which works nicely. :/

Dictionary follow a hash order to speed up lookup.

I'm attempting to simplify my fundraising page, and would like to show exactly how much each donation would help us out. I've listed the options below, but I would like ...

Write a java program that asks a person for his height (in meters) and weight (in kilograms) and
outputs one of the messages: underweight, normal, or obese, using the BMI ...

Before I get into the specific issues, I want to provide some other details:

  • Normally, I work on a live, paid server (even in dev); I realize that is ...
Tags:python
© 2018 2uzhan.com Contact