3

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)
brexling
  • 49
  • 3

2 Answers2

4

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)
daemon24
  • 1,388
  • 1
  • 11
  • 23
1

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
Kaushik NP
  • 6,733
  • 9
  • 31
  • 60
  • When you create an `OrderedDict` from a dictionary literal as shown, you don't really know what order the items will end up in because the **argument** is unordered. To avoid this you should use an ordered iterable like a `list`, `tuple`, or generator to control the order the returned dictionay's contents have. – martineau Nov 11 '17 at 07:02
  • @martineau : have updated – Kaushik NP Nov 11 '17 at 07:08