2

I have this dict posted in request.POST:

<QueryDict: {u'csrfmiddlewaretoken': [u'fhvpUorGAl7LMv4JIJRd0WOEHPkKn6iN'], u'actor_1': [u'first_actor'], u'actor_5': [u'second_actor'], u'actor_55': [u'third_actor'], u'actor_2': [u'fourth_actor']}>

i want to sort it by the keys to have

<QueryDict: {u'actor_1': [u'first_actor'], u'actor_2': [u'fourth_actor'], u'actor_5': [u'second_actor'], u'actor_55': [u'third_actor'], u'csrfmiddlewaretoken': [u'fhvpUorGAl7LMv4JIJRd0WOEHPkKn6iN']}>

Is there a way to sort keys (not values) of a dictionnary ?

Drwhite
  • 1,545
  • 4
  • 21
  • 44
  • 1
    @tea2code that is sorting a dictionary by the values, not the keys? So not quite the same question as far as I can see – Will Sep 05 '13 at 10:58
  • 3
    I copied the wrong link sorry. The correct one: http://stackoverflow.com/questions/9001509/python-dictionary-sort-by-key – tea2code Sep 05 '13 at 10:59

3 Answers3

4

Common dicts are, as mentioned, unordered by nature, but you can use OrderedDicts.

import collections

d = {
    u'csrfmiddlewaretoken': [u'fhvpUorGAl7LMv4JIJRd0WOEHPkKn6iN'], 
    u'actor_1': [u'first_actor'], 
    u'actor_2': [u'fourth_actor']
}

collections.OrderedDict(sorted(d.items()))
Xevelion
  • 859
  • 6
  • 9
  • The simple way is listed in the seconde link given by tea2code: `req_posts = request.POST` `sorted_posts = sorted(req_posts.iterkeys())` – Drwhite Sep 05 '13 at 11:10
2

Dictionaries cannot be sorted. Instead use for example a list.

However you can print out the values sorted by using:

d = {u'csrfmiddlewaretoken': [u'fhvpUorGAl7LMv4JIJRd0WOEHPkKn6iN'], 
 u'actor_1'            : [u'first_actor'], 
 u'actor_5'            : [u'second_actor'], 
 u'actor_55'           : [u'third_actor'], 
 u'actor_2'            : [u'fourth_actor']}

keys = d.keys()
keys.sort()
for key in keys:
   print d[key]

print keys

Result:

[u'first_actor']
[u'fourth_actor']
[u'second_actor']
[u'third_actor']
[u'fhvpUorGAl7LMv4JIJRd0WOEHPkKn6iN']
[u'actor_1', u'actor_2', u'actor_5', u'actor_55', u'csrfmiddlewaretoken']

Which displays all sorted values and last line displaying the sorted keys.

Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119
0

No. Fundamentally, the keys in a Python dictionary are unordered. check the dictionary documentation here

a14m
  • 7,808
  • 8
  • 50
  • 67
Will
  • 73,905
  • 40
  • 169
  • 246
  • No ! they are, see tea2code's link in comment :) – Drwhite Sep 05 '13 at 11:05
  • 2
    @Drwhite **in** a `dict`ionary keys are **not** sorted(i.e. the order in which they are displayed when printing, or yielded when iterating is pseudo-random). tea2code shows a *different* data structure, which does *not* "sort" the keys. It simply keeps track of the order in which the keys were *added* (not their alphabetical order!) – Bakuriu Sep 05 '13 at 11:31