-1

So I'm pretty new to programming, and I'm working on a small text based game for practice. Anyways, here's my problem.

    x=1
    for items in hero.basics:
        print(x, ". ", items, sep = "")
        x += 1

and the dictionary is,

self.basics    = {"Attack" : self.attack, "Potion" : self.potion}

So I need it to display in the same order as the actual dictionary, but it always displays randomly.

Any suggestions?

  • I'm not sure what your problem is but, dictionaries are unordered. – keyser Dec 22 '13 at 00:57
  • It's not random. It is a pretty much deterministic order once the interpreter starts and sets the hash seed. Maybe it's just not what you expected because you forgot to read the docs... – JBernardo Dec 22 '13 at 01:01
  • Why is this question getting those close votes? The answers on the supposed duplicate question tell you why, but don't offer an alternative solution (whereas the answers here both do). – Makoto Dec 22 '13 at 01:04
  • possible duplicate of [Python dictionary keep keys values in same order as declared](http://stackoverflow.com/q/1867861) – jscs Dec 22 '13 at 01:13

2 Answers2

4

Here is a problem: Dictionaries are unordered. They aren't suppose to be ordered, and they aren't stored in order either.

Take a look at this console session:

>>> d = {'a':5, 'b':6, 'c': 3}
>>> d
{'a': 5, 'c': 3, 'b': 6}

See?

However, you can sort it like this while looping through the keys:

for k in sorted(d):

But the dictionary itself, will remain unsorted. Alternatively, you can take a look at collections.OrderedDict (which is a subclass of dict), to really have a sorted dictionary.

keyser
  • 18,829
  • 16
  • 59
  • 101
aIKid
  • 26,968
  • 4
  • 39
  • 65
2

If you really need an ordered dict, then collections.OrderedDictis what you're looking for. From the docs:

Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.

MattDMo
  • 100,794
  • 21
  • 241
  • 231