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(hea开发者_StackOverflowder_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]))
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.
Dictionaries aren't ordered collections. You have to have some other data to keep track of the ordering.
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.
精彩评论