Iterate through Dictionary in order

Viewed 2396

I am trying to iterate through a dictionary in the order I have created the dictionary for example, I want it to print name in this order. Right now it prints in random order.

Order I want :ExtraClick, AutoClick, PackCookies, BakeStand, GirlScouts

code:

self.how_many_buildings = {'ExtraClick': 0,
                               'AutoClick': 0,
                               'PackCookies': 0,
                               'BakeStand': 0,
                               'GirlScouts': 0}
for name in self.how_many_buildings:
    print(name)
2 Answers

Use OrderedDict to maintain order for dictionaries

from collections import OrderedDict

self.how_many_buildings = OrderedDict(('ExtraClick', 0),
                                      ('AutoClick', 0),
                                      ('PackCookies', 0),
                                      ('BakeStand', 0),
                                      ('GirlScouts': 0))
for name in self.how_many_buildings:
    print(name)

Dictionaries do not have order and hence you require external classes that can handle the order too. Something like OrderedDict available in collections module which forms a wrapper class on the base dict class, providing extra functionalities along with all the other basic operations of dict.

Example :

>>> from collections import OrderedDict
>>> d = OrderedDict( [('a',1) , ('b',2) , ('c',3)] )
>>> for key in d: 
        print(key)    
=>  a
    b
    c
Related