0

I have the following list of dictionaries:

[{'160': 1.598,
  '1620': 1.305,
  '26': 4.554,
  '2952': 1.2380,
  '2985': 1.56,
  '3075': 1.04,
  '3222': 0.9721,
  '3388': 1.68,
  '3443': 0.600,
  '361': 2.6682,
  '4': 5.22,
  '601': 2.26,
  '9': 5.032},
 {'1457': 5.625,
  '1469': 25.455,
  '1470': 25.455,
  '605': 5.74627},
 {},
 {'1258': 1.085,
  '2571': 0.982,
  '2943': 2.25,
  '2951': 0.62,
  '2953': 1.84,
  '2958': 0.73,
  '2959': 0.93,
  '2978': 0.67,
  '341': 1.039}]

I want to order each dictionary by the values in descending order, if two values are identical, priority is with the key which is smaller. It is possible that a dictionary be empty as above.

Here is my attempt, by it only does for the first one:

import operator
sorted(mylist[0].items(), key=operator.itemgetter(1),reverse=True)

I construct my list of dictionaries like this:

[{k:v for k,v in d.items() if v == max_vals[k]} for d in mylist]

How can I do it inherently in this step? Without having to do the ordering in a separate line? How can the order be maintained withing the construction step?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
passion
  • 1,000
  • 6
  • 20
  • 47
  • 2
    Dictionaries are not ordered data structures. Have you researched this at all? Tried anything? – jonrsharpe Apr 21 '17 at 07:46
  • python dictionaries are unordered. the order you see when printing them has no meaning. there is an `OrderedDict` in the `collections` module if you really need that (they are way slower though). – hiro protagonist Apr 21 '17 at 07:46
  • 1
    Should the dictionary be on a specific place in the array according to a value in each dictionary? – Daniel Frühauf Apr 21 '17 at 07:47
  • You should look into ordered dicts, they maintain insertion order. – chatton Apr 21 '17 at 07:48
  • FWIW, plain dict in Python 3.6+ _does_ maintain insertion order, but this is currently an implementation detail, and it certainly should **not** be relied on. – PM 2Ring Apr 21 '17 at 07:54
  • @DanielFrühauf I updated my question and it contains more details. – passion Apr 21 '17 at 07:56
  • @jonrsharpe I added my attempts and more details. please have a look thanks – passion Apr 21 '17 at 07:56
  • 1
    *"how can I do it inherently in this step?"* - you could use `sorted(d.items() ...)`, but you'll still have the problem that a dictionary comprehension builds a dictionary, which *isn't an ordered data structure*. – jonrsharpe Apr 21 '17 at 07:59
  • 1
    One **lazy way** to access your dict based on sorted order of value will be to *create a list of keys sorted based on the value and access dict based on sorted keys*. Else you may use [`collections.OrderedDict`](https://docs.python.org/2/library/collections.html#collections.OrderedDict) – Moinuddin Quadri Apr 21 '17 at 08:01

0 Answers0