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

2024-04-19 23:07:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个50个字典的列表,并希望按该字典的“Key2”值排序。你知道吗

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

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

>>>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”的值对字典列表进行排序?你知道吗


Tags: 列表字典排序方式onethreeabcsorted
2条回答

假设每个字典只有一个键,可以执行以下操作:

sorted(list1, key=lambda d: d[next(iter(d))][0]['key2'])

这里:d[next(iter(d))]将给出与d相关联的第一个键的值。当然,字典是无序的,所以“第一”键只有在字典中只有一个键值对时才有意义。。。你知道吗


FWIW,看起来你的数据结构真的妨碍了一个干净的解决方案。一个简单的dict列表似乎是存储数据的更好方法:

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

因为只有一个值的dict和只有一个值的list往往会使容器有点过分。你知道吗

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]获取内部列表的第一个值。你知道吗

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

相关问题 更多 >