Skip to main content
 首页 » 编程设计

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

2025年05月04日14lvdongjie

我有一个包含 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