sorting list of nested dictionaries in python
我有类似的东西
1 2 3 4 5 6 7 8 9 10 11 | [ { "key": {"subkey1":1,"subkey2":"a" } }, { "key": {"subkey1":10,"subkey2":"b" } }, { "key": {"subkey1":5,"subkey2":"c" } } ] |
并且需要:
1 2 3 4 5 6 7 8 9 10 11 | [ { "key": {"subkey1":10,"subkey2":"b" } }, { "key": {"subkey1":5,"subkey2":"c" } }, { "key": {"subkey1":1,"subkey2":"a" } } ] |
多谢!
编辑:我想按子键1排序,以前不清楚。
将
1 | yourdata.sort(key=lambda e: e['key']['subkey'], reverse=True) |
演示:
1 2 3 4 | >>> yourdata = [{'key': {'subkey': 1}}, {'key': {'subkey': 10}}, {'key': {'subkey': 5}}] >>> yourdata.sort(key=lambda e: e['key']['subkey'], reverse=True) >>> yourdata [{'key': {'subkey': 10}}, {'key': {'subkey': 5}}, {'key': {'subkey': 1}}] |
这假定所有顶级字典都有一个
有关更多详细信息和技巧,请参见python sorting howto。
假设要按列表中每个字典的
1 | sorted(yourdata, key=lambda d: d.get('key', {}).get('subkey'), reverse=True) |
1 | sorted(yourdata, reverse=True) |