python - 访问 python 中的字典列表并使用值对其进行排序(嵌套字典)

标签 python list python-2.7 sorting dictionary

我有一个包含 50 部词典的列表,并希望按该词典的“Key2”值进行排序。

list1= [{'outside_key1': [ { 'key1': 'one', 'key2': 'xyz','key3':'three'}]} ,
        {'outside_key2': [ { 'key1': 'one', 'key2': 'abc','key3':'three'}]}]

Key2 可以通过以下方式静态访问:

>>>print list1[0]['outside_key1'][0]['key2']
   xyz

现在根据 'key2' 排序,例如:

sorted_list = sorted(list1, key=lambda k: k[???])

最终按值排序变为:

[{'outside_key2': [ { 'key1': 'one', 'key2': 'abc','key3':'three'}]} ,
 {'outside_key1': [ { 'key1': 'one', 'key2': 'xyz','key3':'three'}]}]

所以我的问题是:
1. 如何动态访问'Key2'的值?
2. 如何根据 'Key2' 的值对字典列表进行排序?

最佳答案

list1= [{'outside_key1': [ { 'key1': 'one', 'key2': 'xyz','key3':'three'}]} ,
        {'outside_key2': [ { 'key1': 'one', 'key2': 'abc','key3':'three'}]}]
sort_on = "key2"
decorated = [(dict_.values()[0][0][sort_on], dict_) for dict_ in list1]
decorated.sort()
result = [dict_ for (key, dict_) in decorated]
print result

dict_.values() 获取外dic值,第一个[0]获取outside_key1的值,第二个[0]获取inner的第一个值列表。

Here's the fastest way to do it, as it avoids using a custom comparison function, instead using builtin comparisons. You can get more information from Sorting Lists of Dictionaries

关于python - 访问 python 中的字典列表并使用值对其进行排序(嵌套字典),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33205921/

相关文章:

.exe 中的 Python 子进程

python - Keras:CuDNN 不可用?

python - Pandas 合并时间序列,concat/append/...?

python - Django , python :AttributeError: 'NoneType' object has no attribute '_meta'

list - 列表中最新的非空值

Django:list_filter 和外键字段

python - 为特定列写带双引号的 csv 文件不起作用

python - 需要将csv文件合并成一个然后将csv导入到mysql中的表中

python - 使用 Python 搜索具有 MAC 地址的主机

c# - 当我不知道 (T) 的类型时如何反序列化通用列表 <T>?