So i have initialized a forloop that iterates over a range of objects, where range starts from 1 and ends at the maximum number of fields a model has
for count in range(1, len(field_list)):
f_val = getattr(instance, field_list[count])
field_values[field_list[count]] = f_val
print "field_values: ", field_values
The f_val
variable calculates the field value using model_instance.field_name
and inserts the field name and field value as key value pairs in 'field_values' dictionary. When i print field_values
i get:
field_values: {'descr': u'ggg'}
field_values: {'descr_en': u'sg', 'descr': u'ggg'}
field_values: {'notes': u'ddddf', 'descr_en': u'sg', 'descr': u'ggg'}
so what i want to do now is reverse the order of the key value pairs such that i have {'descr': u'ggg', 'descr_en': u'sg', 'notes': u'ddddf'}
. Thus, I used reversed()
in my initial loop (for count in reversed(range(1, len(field_list))):
) but my dictionary although it started with the last key value pair instead of the first still the final output was the same as in the beginning.
field_values: {'notes': u'ddddf'}
field_values: {'notes': u'ddddf', 'descr_en': u'sg'}
field_values: {'notes': u'ddddf', 'descr_en': u'sg', 'descr': u'ggg'}
So I would like to know why this is happening?? does it sort my dictionary by default?? And if this approach does not work what other approaches could i follow?