-3

i wrote the following code and when this code executes, the output is like

one:33.75%

zero: 32.98%

two: 33.27%

my question is, why isnt it in order and how can i do that?

import random 
a=0
dict = {"zero":0,"one":0,"two":0}
while a < 10000:
    a +=1
    b = random.randrange(0,3)
    if b == 0:
        dict["zero"] += 1
    elif b == 1:
        dict["one"] += 1
    elif b == 2:
        dict["two"] += 1
for item in dict:
    dict[item] /= 100
    dict[item] = str(dict[item])+"%"
    print(item + ":" + dict[item])  
awesoon
  • 32,469
  • 11
  • 74
  • 99
Anvit
  • 218
  • 2
  • 12

1 Answers1

5

Regular dictionaries do not have an order. Instead, use OrderedDict from the collections module.

import collections

key_value_pairs = [('zero', 0),
                   ('one', 0),
                   ('two', 0)]

dict = collections.OrderedDict(key_value_pairs)

Then you can do everything like you've done above.

Jenner Felton
  • 787
  • 1
  • 9
  • 18