2

Possible Duplicate:
How do you retrieve items from a dictionary in the order that they’re inserted?

I have an issue with django view and template

After getting details related to a meeting like

        for meeting in get_meetings:
           if meeting.venue_id ==None:
                 mee_data = {} 
                 mee_data['id'] = meeting.id
                 getdate = meeting.meeting_datetime
                 mee_data['date'] = getdate.strftime("%Y-%m-%d")
                 mee_data['end_time'] = meeting.end_time
                 mee_data['meeting_duration'] = meeting.meeting_duration 
                 mee_data['start_time'] = meeting.start_time 
                 mee_data['meetingID'] = meeting.meetingID
                 mee_data['id'] = meeting.id
                 mee_data['start_time'] = meeting.start_time 

                 mee_data['name'] = meeting.name

                 getall.append(mee_data) 

Where getall is a list i have declared above

Now after appending the dictionary data.

I am expecting the result in my template is like

[{"id": "REG_431103567", "date": "", "end_time": "", "meeting_duration": "", "start_time": "2012-10-29", "meetingID": 192dnjd, "name": "TEsts"},...]

basically the order of keys but unfortunately the result is coming like .

[{"meetingID": "REG_431103567", "start_time": "", "meeting_duration": "", "end_time": "", "date": "2012-10-29", "id": 192, "name": "TEsts"},...]

Please suggest me what should i do here so that i could get the keys and their corresponding values in proper way .

Thanks

3

2 Answers 2

6

I'd suggest use an OrderedDict to get the data in the order it was inserted.

Dictionaries don't maintain the order but an OrderedDict which is a sub-class 0f dict can maintain the order.

Example:

>>> from collections import OrderedDict
>>> d=OrderedDict()
>>> d["key1"]="foo"
>>> d["key2"]="bar"
>>> d
OrderedDict([('key1', 'foo'), ('key2', 'bar')])

Note: OrderedDict was introduced in python 2.7, so will not work in previous versions.

3
  • @user1667633 Note that OrderedDict was introduced in python 2.7 only, so will not work in previous versions. Nov 2, 2012 at 9:24
  • Note that there are implementations available for previous versions of Python. See the answer to the question that is marked as duplicate.
    – moooeeeep
    Nov 2, 2012 at 9:34
  • @moooeeeep Interestingly even the question is before the time of python 2.7 release. Thanks for the link. Nov 2, 2012 at 9:47
1

Use OrderedDict instead of normal dict.

from collections import OrderedDict

for meeting in get_meetings:
           if meeting.venue_id ==None:
                 mee_data = OrderedDict()
                 ...

Not the answer you're looking for? Browse other questions tagged or ask your own question.