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}
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}
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.