0

I have a dictionary like this:

dic = {'jack':15,'sara':'20','bob':13,'abby':13}

I only want to sort the keys that have similar values just like 'bob' and 'abby'. I need to get this output:

dic = {'jack':15,'sara':'20','abby':13,'bob':13}
Sam
  • 379
  • 2
  • 10
  • A Python dictionary is not an ordered data type, so there is no way to determine the order of the keys here. You're probably looking for something like Python's [OrderedDict](https://docs.python.org/3/library/collections.html#collections.OrderedDict). – Paul Götze Mar 25 '21 at 11:05
  • 1
    What is the reason for needing to sort them? Quite often if you find yourself wanting the sort a dictionary then it means you might actually want a different data structure. – Kemp Mar 25 '21 at 11:07

1 Answers1

1

Here is one approach where you can create an inverted dictionary first and then insert back in a sorted() manner.

Since the dictionaries maintain insertion order by default from Python3.6+, you can be sure that they keys are in ordered manner. Read more about dictionary keys ordering in the order of keys in dictionaries.

dic = {'jack':15,'sara':20,'bob':13,'abby':13}
invertedDic = {}
for k, v in dic.items():
    invertedDic.setdefault(v, []).append(k)
    
dic = {}
for key, val in invertedDic.items():
    for v in sorted(val):
        dic[v] = key

Having said that as Kemp pointed, you should look at the requirement of ordering and probably a different data structure might be better suited for storing the data.

You could also have a look at OrderedDict as Paul pointed depending on the requirement.

Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35