0

I'm having trouble looping through my dictionary.

max_money = {
    "FIFTY" : 50,
    "TWENTY": 20,
    "TEN"   : 10,
    "FIVE"  : 5,
    "TWO"   : 2,
    "ONE"   : 1,
    "HALF DOLLAR": float(.50),
    "QUARTER"    : float(.25), 
    "DIME"       : float(.1), 
    "NICKEL"     : float(.05), 
    "PENNY"      : float(.01)
}

when i test loop through (max_money), it doesn't display the dictionary in the order i typed it above. Can anyone explain why and how to properly display it in the order above?

sample output:

for i in max_money:
print(max_money[i])

0.01
20
10
2
0.5
1
5
0.10000000000000001
50
0.050000000000000003
0.25

goal:

50
20
10
5
2
1
.50
.1
.05
.01
msw
  • 42,753
  • 9
  • 87
  • 112
A K
  • 1,464
  • 2
  • 12
  • 18

1 Answers1

1

Dictionaries do not have a sense of order, the actual order depends on the insertion and deletion history of the dictionary and the python implementation, that is the reason why you are getting back the elements in an arbitrary order.

If order is important for you, you should use collections.OrderedDict , it keeps the order in which you added the elements.

Example -

>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> d[1] = 2
>>> d[2] = 3
>>> d[3] = 4
>>> for i in d:
...     print(d[i])
...
2
3
4
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176