Mr. Polywhirl
Mr. Polywhirl

Reputation: 48693

Python sort a dictionary by the sum of its items

I have the following data structure that I need to sort. For each bin which is a group of items with the same height, I need to get the sum of the areas and the sum of the weights and order the bins by the ratio.

bins = {
  12 : [
    {
      length : 12
      width  : 24
      weight : 50
    },
    {
      length : ...
      width  : ...
      weight : ...
    }
  ]
  52 : ...
  24 : ...
  36 : ...
} 

The keys in bins is the height and in each bin there is a list of items.

I have tried to come up with something, but I have had no luck.

bins = sorted(bins, key=lambda bin: (
  sum([item['Length']*item['Width'] for item in bins[bin]]) /
  sum([item['Weight'] for item in bins[bin]])
), reverse=True)

The problem is this returns a list. Is there anyway to retain the dictionary object. Should I cast it as an iterator?

Upvotes: 0

Views: 864

Answers (2)

Félix Cantournet
Félix Cantournet

Reputation: 2001

Sorted() returns a list because dictionaries cannot be sorted. The structure doesn't store order.

Another solution is to use OrderedDict. This is a dictionary that remembers in which order you inserted the items. So you can't really "Sort" and OrderedDict, but you could store the result or the sorted() function in an new OrderedDict.

See this question for more details :

How to sort OrderedDict of OrderedDict - Python

Upvotes: 2

BrenBarn
BrenBarn

Reputation: 251468

Dictionaries are inherently unordered. You can't sort them. You could google around for implementations of a "SortedDict" which is like a dictionary but also allows sorting.

Upvotes: 1

Related Questions