-2

Could anyone help me out with the dict in python ?

I made a dict with a print statement which is as following :

role = {
    'user': 1,
    'moderator': 2,       
    'admin': 3
}

for r in role:
    print role[r]

I thought the result would be

1
2
3

but it actually printed out

2
3
1

Can anyone tell me why?

sinned
  • 698
  • 1
  • 7
  • 17
KoooPooo
  • 19
  • 4
  • 4
    Because dictionaries are unordered in Python. (From 3.6 the most popular interpreter makes them ordered, but this is considered an implementation detail). – Willem Van Onsem Oct 14 '17 at 12:43
  • 4
    Possible duplicate of [Key-ordered dict in Python](https://stackoverflow.com/questions/1319763/key-ordered-dict-in-python) – Vasili Syrakis Oct 14 '17 at 12:46
  • 3
    This is clearly stated in the docs: https://docs.python.org/2/faq/design.html#how-are-dictionaries-implemented – rainer Oct 14 '17 at 12:48

2 Answers2

0

From the docs:

... no sorted order of the keys is maintained, and traversing the array as the .keys() and .items() do will output the dictionary’s content in some arbitrary jumbled order.

So when you stick items like this into a dict, you can't guarantee any order. If you need to maintain an order, you will need to use a list instead.

If you want to print these items out based on the numbers in the values, you can do:

for r in sorted(role.items(), key=lambda x: x[1]):
    print r

Output:

('user', 1)
('moderator', 2)
('admin', 3)

Or just store them in a list:

role = ['user', 'moderator', 'admin']
for r in role:
    print r
jpyams
  • 4,030
  • 9
  • 41
  • 66
  • @KoooPooo welcome to StackOverflow! If the answers helped you, the best way to say 'thank you' is to upvote them, and if one solved your problem, go ahead and mark it as the accepted answer – jpyams Oct 17 '17 at 17:40
0

a regular dictionary doesn't maintain the order by which the elements are inserted, giving that a dictionary is just a form of a hashtable, whereas you could use an ordered dictionary link

rachid el kedmiri
  • 2,376
  • 2
  • 18
  • 40