如何根据键内的值对字典进行排序?

How to sort a dict by the values inside its keys?

所以我有这样的东西:

[
{
    "arg1":
          {"valueone" : 2, "valuetwo": 5"},
},
{
    "arg2":
          {"valueone" : 7, "valuetwo": 3"},
},
{
    "arg3":
          {"valueone" : 3, "valuetwo": 7"},
},
{
    "arg4":
          {"valueone" : 4, "valuetwo": 6"},
},
{
    "arg5":
          {"valueone" : 9, "valuetwo": 5"},
},

]

我想按 valueone 对它们进行排序。我了解 OrderedDict,但是我在执行此操作时遇到了一些麻烦。

预期结果为:

[
{
    "arg5":
          {"valueone" : 9, "valuetwo": 5"},
},
{
    "arg2":
          {"valueone" : 7, "valuetwo": 3"},
},
{
    "arg4":
          {"valueone" : 4, "valuetwo": 6"},
},
{
    "arg3":
          {"valueone" : 3, "valuetwo": 7"},
},

{
    "arg1":
          {"valueone" : 2, "valuetwo": 5"},
},


]

如有任何帮助,我们将不胜感激。

可以将sorted的关键参数与reverse=True结合使用,例如:

data = [
    {"arg1": {"valueone": 2, "valuetwo": "5"}},
    {"arg2": {"valueone": 7, "valuetwo": "3"}},
    {"arg3": {"valueone": 3, "valuetwo": "7"}},
    {"arg4": {"valueone": 4, "valuetwo": "6"}},
    {"arg5": {"valueone": 9, "valuetwo": "5"}}
]

result = sorted(data, key=lambda x: next(x["valueone"] for x in x.values()), reverse=True)
print(result)

输出

[{'arg5': {'valuetwo': '5', 'valueone': 9}}, {'arg2': {'valuetwo': '3', 'valueone': 7}}, {'arg4': {'valuetwo': '6', 'valueone': 4}}, {'arg3': {'valuetwo': '7', 'valueone': 3}}, {'arg1': {'valuetwo': '5', 'valueone': 2}}]

试试这个

>>> import pprint
>>> pprint.pprint(x)
[{'arg1': {'valueone': 2, 'valuetwo': 5}},
 {'arg2': {'valueone': 7, 'valuetwo': 3}},
 {'arg3': {'valueone': 3, 'valuetwo': 7}},
 {'arg4': {'valueone': 4, 'valuetwo': 6}},
 {'arg5': {'valueone': 9, 'valuetwo': 5}}]
>>> sorted_ = sorted(x, key=lambda z: z[z.keys()[0]]['valueone'], reverse=True)
>>> pprint.pprint(sorted_)
[{'arg5': {'valueone': 9, 'valuetwo': 5}},
 {'arg2': {'valueone': 7, 'valuetwo': 3}},
 {'arg4': {'valueone': 4, 'valuetwo': 6}},
 {'arg3': {'valueone': 3, 'valuetwo': 7}},
 {'arg1': {'valueone': 2, 'valuetwo': 5}}]