2

I have this Django query where I get some information from different databases, which I want to expose to the front end:

specifics = PageData.objects.filter(page_id__in=page_ids).values('page_id'). \
                annotate(views=Count('page_id')).                            \
                values('views', 'page__title', 'page__content_size')

that gives me in turn a list of dictionaries - the prompt is for list(specifics):

[
{'page__content_size': 19438L,
  'page__title': u'Bosch Tassimo Charmy anmeldelse. Positivt: Bryggehastighed. Negativt: Placering af vandtanken.  | 96 Grader',
  'views': 5},
 […]
 {'page__content_size': 19395L,
  'page__title': u'Banwood First Go Balance Bike - studiominishop.com',
  'views': 1}
]

I would like to be able to arrange the order of the keys in each dictionary, that means in a required and specific order I am provided. The order would always be the same for each element in the list.

Is there any way to do it in Django or in Python?

Mattia Paterna
  • 1,268
  • 3
  • 15
  • 31

3 Answers3

2

You probabily need this:

import collections

OrderedDict dict subclass that remembers the order entries were added

Documentation here: https://docs.python.org/3/library/collections.html#collections.OrderedDict

Here you can find a full example:

https://pymotw.com/2/collections/ordereddict.html

d = collections.OrderedDict()
d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
d['d'] = 'D'
d['e'] = 'E'

for k, v in d.items():
    print k, v`

Hope this help, Ciao!

Community
  • 1
  • 1
Mattia
  • 961
  • 13
  • 25
1

This is actually related to python. Here is the cross-reference to the same question which already answered.

Sorting dictionary keys in python

You can only get a sorted representation of the key list.

Indika Rajapaksha
  • 1,056
  • 1
  • 14
  • 36
  • maybe I've been unclear in the explanation, I'd like to arrange the order of the keys, not sort them. And I need the dictionary, not a sorted representation. I'll update my question. – Mattia Paterna Jun 16 '17 at 10:06
  • @MattiaPaterna You cannot sort the dictionary. Python internally change the order of keys when storing values. – Indika Rajapaksha Jun 16 '17 at 10:08
1

One way is to use values_list instead of values. However this returns list of tuples instead of list of dictionaries but the order is always the same in all elements.

specifics = PageData.objects.filter(
    page_id__in=page_ids).values('page_id').annotate(
    views=Count('page_id')).values_list(
    'views', 'page__title', 'page__content_size')

Values will always be in the order specified in values_list but a tuple instead of dictionaries.

[
    (5, u'Bosch Tassimo Charmy anmeldelse. Positivt: Bryggehastighed. Negativt: Placering af vandtanken.  | 96 Grader', 19438L),
     […]
    (1, u'Banwood First Go Balance Bike - studiominishop.com', 19395L)
]

Python dictionary does not guarantee the order

Raj Subit
  • 1,487
  • 2
  • 12
  • 23