简体   繁体   中英

sorting dict values without sorted function in Python

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)

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM