简体   繁体   English

在python中对dict值排序而没有排序功能

[英]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. 实际上使smlkey1列表具有第一个包含最小值的键作为唯一元素,而第二个包含最小键的键作为唯一元素。
(The syntax x = [....] will make x a list, even if there is only one element). (即使只有一个元素,语法x = [....]也会使x成为列表)。

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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