按嵌套键对字典排序

时间:2019-07-09 19:53:55

标签: python dictionary

考虑以下形式的字典:

git reset --soft develop # put all changes related to your PR into the index, ready to commit
git commit -m "My PR changes"

我想按嵌套的dic键dic = { "First": { 3: "Three" }, "Second": { 1: "One" }, "Third": { 2:"Two" } }

对其进行排序

我尝试以以下方式使用lambda函数,但它返回“ KeyError:0”

(3, 1, 2)

预期输出为:

dic = sorted(dic.items(), key=lambda x: x[1][0])

实质上,我想知道的是如何独立于主字典键指定嵌套键。

2 个答案:

答案 0 :(得分:4)

在lambda函数中,x是键值对,x[1]是值,其本身就是字典。 x[1].keys()是其键,但是如果要通过其索引获取其唯一项,则需要将其转换为列表。因此:

sorted(dic.items(), key = lambda x: list(x[1].keys())[0])

计算结果为:

[('Second', {1: 'One'}), ('Third', {2: 'Two'}), ('First', {3: 'Three'})]

答案 1 :(得分:0)

dic = {'First': {3: 'Three'}, 'Second': {1: 'One'}, 'Third': {2: 'Two'}}
sorted_list = sorted(dic.items(), key=lambda x:list(x[1].keys())[0])
sorted_dict = dict(sorted_list)
print(sorted_dict)

您需要首先获取嵌套字典的键,然后将其转换为list并对其第一个索引进行排序。您将得到一个排序列表。您只需使用dict()将此列表转换为字典即可。希望对您有所帮助。此代码段适用于python3。

相关问题