[Answered ]-How to add data in a dictionary in the same order of the list containing the keys in Django?

2👍

dict no keeping order. You could use for that OrderedDict from collections. From docs:

Return an instance of a dict subclass, supporting the usual dict
methods. An OrderedDict is a dict that remembers the order that keys
were first inserted. If a new entry overwrites an existing entry, the
original insertion position is left unchanged. Deleting an entry and
reinserting it will move it to the end.

For your case:

from collections import OrderedDict
data = OrderedDict()

for i in myList:
    data[i] ={'name':"jack",'date': "2015-10-01"}


In [616]: data
Out[616]: 
OrderedDict([('a', {'date': '2015-10-01', 'name': 'jack'}),
             ('b', {'date': '2015-10-01', 'name': 'jack'}),
             ('c', {'date': '2015-10-01', 'name': 'jack'}),
             ('d', {'date': '2015-10-01', 'name': 'jack'})])

Leave a comment