根据键名不同的值对字典列表进行排序 [英] Sort list of dictionaries based on values where keys have different names

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

问题描述

我有一个字典列表,如下所示:

I have a list of dictionaries which look like the following:

my_list = [
          {'1200' : [10, 'A']},
          {'1000' : [24, 'C']},
          {'9564' : [6, 'D']},
          ]

列表中的所有词典都有一对键值对.

All dictionaries in the list have one key-value pair.

我想根据每个字典值的第一个元素(列表)对它进行排序,因此排序后的列表看起来像:

I want to sort it based on the first element of each dictionaries value which is a list, so the sorted list would look like:

my_list_sorted = [
          {'9564' : [6, 'D']},
          {'1200' : [10, 'A']},
          {'1000' : [24, 'C']},
          ]

如您所见,这些键具有不同的名称,这就是为什么我无法使用以下帖子中的答案的原因:

As you can see the keys have different names and that's why I could not use answers from, for example, the following post: How do I sort a list of dictionaries by a value of the dictionary?

推荐答案

您可以使用values()访问dict元素:

sorted(my_list, key=lambda x: x.values()[0][0])

输出:

[
  {'9564': [6, 'D']},
  {'1200': [10, 'A']},
  {'1000': [24, 'C']}
]

这假定每个条目都包含一个至少包含一个元素的列表.

This assumes that each entry contains a list with at least one element.

编辑PYTHON 3

正如@cᴏʟᴅsᴘᴇᴇᴅ指出的那样,values()不会在python3中返回列表,因此您必须这样做:

As @cᴏʟᴅsᴘᴇᴇᴅ points out, values() does not return a list in python3, so you'll have to do:

sorted(my_list, key=lambda x: list(x.values()[0])[0])

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

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