How can I sort a dictionary by value without using lambda function and without importing python libraries?
Asked
Active
Viewed 378 times
-1
-
You can define a named function instead of using `lambda`. – Barmar Jan 11 '22 at 20:55
-
1Maybe you could explain the point of trying to accomplish this with avoiding common parts of the language. Is this a homework assignment? – Mark Jan 11 '22 at 21:06
-
@Mark: Of course it's homework. Sefineh: Please see [How do I ask and answer homework questions?](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) – martineau Jan 11 '22 at 22:24
2 Answers
2
This is a one-liner. You can create a new dictionary by use of a dictionary comprehension where you iterate over the keys sorted by value.
d = {'g': 1, 'd': 6, 'c': 5, 'b': 4, 'z': 0, 'a': 1}
sorted_d = {k: d[k] for k in sorted(d, key=d.get)}
print(sorted_d)
The output in this example is:
{'z': 0, 'g': 1, 'a': 1, 'b': 4, 'c': 5, 'd': 6}
UPDATE: Only in Python > 3.7, the resulting order of the keys will be guaranteed to be in insertion order. Older versions of Python do not guarantee this solution to work (thanks, @baskettaz!).
-
The keys are not reliable for such an action, this is not a good solution in this case. – baskettaz Jan 11 '22 at 21:56
-
@baskettaz, the sorted dictionary is created with all of the keys sorted by means of their corresponding value. In this case, no key is left out, so the new dictionary is the same size of the original dictionary and contains all the original key:value pairs. How come isn't it reliable? – Jan 11 '22 at 22:00
-
When hash table grows or shrinks it may re-balance buckets and change the order.This is not promised in the language definition. In the newer version it could be (from 3.7 and later) but I wouldn't rely on it. For more information please see: https://stackoverflow.com/questions/35237160/how-reliable-is-python-s-dictionary-ordering – baskettaz Jan 11 '22 at 22:07
-
@baskettaz, how can the hash table grow or shrink in this case? The keys of the original dictionary and the sorted dictionary are the same. Although I think I see your point, in Python < 3.7, the resulting order of the keys is not guaranteed to remain the same throughout the execution of a given program. Thanks for the info! – Jan 11 '22 at 22:20
0
Here is my implementations.
dictionary={'a':1,'d':6,'c':5,'b':4,"z":0}
listKeySorted=[None]*len(dictionary)
listVal=list(dictionary.values())
listKey=list(dictionary.keys())
listValSorted=sorted(listVal)
for i in range(len(listVal)):
index=listValSorted.index(listVal[i])
listKeySorted[index]=listKey[i]
sortedDictionary=zip(listKeySorted,listValSorted)
print(dict(sortedDictionary))
output: {'z': 0, 'a': 1, 'b': 4, 'c': 5, 'd': 6}
-
Seems problematic with input like: `{'a':1,'d':6,'c':5,'b':4,'z':0,'g':1}` – Mark Jan 11 '22 at 20:59
-
You should put your own attempt in your question (assuming it's not working and you can't figure-out why). – martineau Jan 11 '22 at 22:26