根据字典键的值对它们进行排序 [英] Sorting dictionary keys based on their values

查看:185
本文介绍了根据字典键的值对它们进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的python字典设置

I have a python dictionary setup like so

mydict = { 'a1': ['g',6],
           'a2': ['e',2],
           'a3': ['h',3],
           'a4': ['s',2],
           'a5': ['j',9],
           'a6': ['y',7] }

我需要编写一个函数,该函数根据排序的列来返回列表中的有序键,例如,如果我们要对mydict [key] [1](升序)进行排序

I need to write a function which returns the ordered keys in a list, depending on which column your sorting on so for example if we're sorting on mydict[key][1] (ascending)

我应该这样收到清单

['a2', 'a4', 'a3', 'a1', 'a6', 'a5']

除了具有多个键具有相同值的列(例如)时,它通常可以工作. 'a2':['e',2]和'a4':['s',2].在这种情况下,它会像这样返回列表

It mostly works, apart from when you have columns of the same value for multiple keys, eg. 'a2': ['e',2] and 'a4': ['s',2]. In this instance it returns the list like so

['a4', 'a4', 'a3', 'a1', 'a6', 'a5']

这是我定义的功能

def itlist(table_dict,column_nb,order="A"):
    try:
        keys = table_dict.keys()
        values = [i[column_nb-1] for i in table_dict.values()]
        combo = zip(values,keys)
        valkeys = dict(combo)
        sortedCols = sorted(values) if order=="A" else sorted(values,reverse=True)
        sortedKeys = [valkeys[i] for i in sortedCols]
    except (KeyError, IndexError), e:
        pass
    return sortedKeys

例如,如果我想对数字列进行排序,就这样

And if I want to sort on the numbers column for example it is called like so

sortedkeysasc = itmethods.itlist(table,2)

有什么建议吗?

保罗

推荐答案

使用起来会容易得多

sorted(d, key=lambda k: d[k][1])

(以d为词典)?

这篇关于根据字典键的值对它们进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆