Reputation: 187
I want to sort values of dictionary in list without using sort function.I tried below but its not working
dict1={"one":1,"two":2,"three":3}
list1=[]
for i in range(len(dict1)):
sml=[a for a in dict1.values() if a ==min(dict1.values())]
key1=[k for k,v in dict1.items() if v ==min(dict1.values())]
del dict[key1]
list1.append(sml)
print(list1)
Upvotes: 3
Views: 7600
Reputation: 1772
Your approach is almost there. Your only mistake is that the lines
sml=[a for a in dict1.values() if a ==min(dict1.values())]
key1=[k for k,v in dict1.items() if v ==min(dict1.values())]
actually make sml
and key1
lists with the first one containing the smallest value as its only element and the second containing the key of the smallest value as its only element.
(The syntax x = [....]
will make x
a list, even if there is only one element).
So everything will be fixed by making those lines as:
sml=[a for a in dict1.values() if a ==min(dict1.values())][0]
key1=[k for k,v in dict1.items() if v ==min(dict1.values())][0]
Upvotes: 1