Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iteration in python dictionary

I populate a python dictionary based on few conditions.

My question is:

can we retrieve the dictionary 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]))
like image 988
Hulk Avatar asked Dec 29 '22 09:12

Hulk


1 Answers

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.

like image 57
Alex Martelli Avatar answered Jan 19 '23 06:01

Alex Martelli