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

Community
  • 1
  • 1
user1667633
  • 4,449
  • 2
  • 16
  • 21
  • See http://stackoverflow.com/a/2030935/647772 –  Nov 02 '12 at 09:18
  • 2
    Dictionaries in python are unordered. Use http://docs.python.org/2/library/collections.html#collections.OrderedDict – Artsiom Rudzenka Nov 02 '12 at 09:19
  • 2
    Have you considered handling it in the template by showing each attribute separately? I mean, the dict formatting isn't going to look good in webpage output anyway... – Karl Knechtel Nov 02 '12 at 09:53

2 Answers2

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.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
1

Use OrderedDict instead of normal dict.

from collections import OrderedDict

for meeting in get_meetings:
           if meeting.venue_id ==None:
                 mee_data = OrderedDict()
                 ...
Rag Sagar
  • 2,314
  • 1
  • 18
  • 21