1

I have a dictionary in which there are integer keys and their integer values, one to one. Like,

x = { 24:13, 32:2, 5:11, 88:34 }

Is there a way to sort it in decreasing order as key/value?

  • Dictionaries, in general, have no order. – Dani Mesejo Jan 05 '19 at 22:00
  • @DanielMesejo it sounds really nice. Let's make an order for them ((: – Soner from The Ottoman Empire Jan 05 '19 at 22:01
  • 1
    They are ordered now, if you are using, Python 3.6+. Otherwise use an OrderedDict – Dani Mesejo Jan 05 '19 at 22:02
  • @DanielMesejo the ordering according to what? – Soner from The Ottoman Empire Jan 05 '19 at 22:03
  • 1
    python 3.7 guarantees insert order on dicts. You have to re-insert in correct order. `x = {sorted(x.items)}` to sort by key ascending - use sort(...,key=...) for other ways to sort IPython gives you the same as sideeffect of implementation on Python 3.6+, you can use collections.OrderedDict in python 3.6 and earlier. All only give you insert order though. See https://docs.python.org/3.7/library/collections.html#collections.OrderedDict – Patrick Artner Jan 05 '19 at 22:04
  • @PatrickArtner the ordering according to what? And what I wish to do? – Soner from The Ottoman Empire Jan 05 '19 at 22:04
  • Insertion of the elements in the dict – Dani Mesejo Jan 05 '19 at 22:05
  • @PatrickArtner Well, what is the relationship of this property with my wish? and marked as duplication? – Soner from The Ottoman Empire Jan 05 '19 at 22:06
  • 1
    @snr in Python 3.6+ try: `dict(sorted(x.items(), key=lambda x: x[0] / x[1]))` – Dani Mesejo Jan 05 '19 at 22:09
  • 1
    The relationship is: Dictionary are unordered (pre 3.7 non IPython, pre 3.6 IPython) and guaranteed to be Insert-Ordered from 3.7 on. If you want to order _your_ dictionary _however_ you need to create it new and insert the key:values in the order you want. If you want to sort by key: `x = {sorted(x.items())}` - if you want to get fancier you can use the `sorted(iterable, key= .....)` to specify the key as fancy as you like. Both topics are touched in the main duplicates (Are dictionaries ordered in Python 3.6+? ) answers - sorting in the 2nd one more specifically. – Patrick Artner Jan 05 '19 at 22:10
  • 1
    Ipython isn't a different interpreter, it's an augmented REPL, and the ordering is the same – juanpa.arrivillaga Jan 05 '19 at 22:46

0 Answers0