views:

100

answers:

3

I populate a python dictionary based on few conditions,

My question is can we retrieve in the same order as it is populated.

          questions_dict={}  

              data = str(header_arr[opt]) + str(row)
              questions_dict.update({data : xl_data})
              valid_xl_format = 7
              if (type.lower() == "ma" or type.lower() == "mc"):
                      data = str(header_arr[opt]) + str(row)
                      questions_dict.update({data : xl_data})
                      valid_xl_format = 7

After populating if i iterate it is not in the order it is populated

     for k in questions_dict:
          logging.debug("%s:%s" %(k,questions_dict[k]))
+2  A: 

Dictionaries aren't ordered collections. You have to have some other data to keep track of the ordering.

controlfreak123
+8  A: 

To keep track of the order in which a dictionary is populated, you need a type different than dict (commonly known as "ordered dict"), such as those from the third-party odict module, or, if you can upgrade to Python 2.7, collections.OrderedDict.

Alex Martelli
What happens when two items map to the same key during insertion? Does it just remember the last insertion and use that ordering and forget the first insertion ever happened? Update: That solution was easy to find... it retains the original insertion position.
Derek Litz
A: 

the reason dictionaries are efficient is that the keys are mapped to objects called hashes and the dictionaries internally stores your values associated to the key's hashes. so when you loop over your entries, this is related to the order of the hashes, not the original keys.

Nicolas78