0

I have a Dictionary like

{'A': {'frequency': 4}, 'B': {'frequency': 2}, 'C': {'frequency': 7}}

How would I be able to sort this by the "frequency" attribute?

martineau
  • 119,623
  • 25
  • 170
  • 301
Daniel Pan
  • 33
  • 1
  • 6
  • Related: [Sort nested dictionary by value, and remainder by another value, in Python](//stackoverflow.com/q/4110665) – Aran-Fey Sep 20 '18 at 17:40
  • FYI, `"frequency"` is a **key** in the sub-dictionaries, not an attribute of them. Also regular dictionaries can't be sorted prior to Python 3.6—so would you please be more exact about what version you're using. – martineau Sep 20 '18 at 18:15

2 Answers2

1

sorted(a, key=lambda x: (a[x]['frequency']))

To keep it ordered by request from the comments:

from collections import OrderedDict OrderedDict(sorted(a.items(), key=lambda x: x[1]['frequency']))

tlm
  • 952
  • 10
  • 20
  • Thanks, so that worked and resulted in ['B', 'A', 'C']. Would it be possible to keep the frequency attribute in the new sorted list so it would look like ['B' : {'frequency': 2}, 'A' : {'frequency': 4}, 'C' : {'frequency': 7}]? – Daniel Pan Sep 20 '18 at 17:43
  • Dictionaries can't be sorted because they are by nature orderless. You could do something like this, though: `OrderedDict(sorted(a.items(), key=lambda x: x[1]['frequency']))`. You'd have to `from collections import OrderedDict` first. For more about sorting dictionaries as well, I would also look at this SO answer: https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value – tlm Sep 20 '18 at 17:54
1

dictionaries are not order in python. if you need to order the dictionary . better to use OrderedDict from collections modules

In [24]: from collections import OrderedDict
    ...: d = {'A': {'frequency': 4}, 'B': {'frequency': 2}, 'C': {'frequency': 7}}
    ...:
    ...: ord_a = OrderedDict(sorted(ord_d.items(), key = lambda x: x[1]['frequency']))
    ...:
    ...:

In [25]:

In [25]: print(ord_a)
OrderedDict([('B', {'frequency': 2}), ('A', {'frequency': 4}), ('C', {'frequency': 7})])
katamit
  • 76
  • 4