在Python中如何按“子键”对字典排序

2024-05-13 19:47:31 发布

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

我能得到一些关于如何做的指导吗

变数

people = {'adam': {'distance': 14, 'age': 22, 'height': 1.3}, 'charles': {'distance': 3, 'age': 37, 'height': 1.4}, 'jeff': {'distance': 46, 'age': 42, 'height': 1.6}}

按子键“距离”对人员变量排序后的预期输出

people = {'charles': {'distance': 3, 'age': 37, 'height': 1.4}, 'adam': {'distance': 14, 'age': 22, 'height': 1.3}, 'jeff': {'distance': 46, 'age': 42, 'height': 1.6}}

Tags: 距离age人员排序peopledistance指导height
3条回答

大多数答案提供了一种基于旧词典内容创建新词典的方法。如果只想对现有字典的键重新排序,可以执行类似的操作:

for k in sorted(people, key=lambda x: people[x]['distance']):
    people[k] = people.pop(k)

当一个键被移除时,它也会从迭代顺序中移除。将其添加回将使其成为迭代顺序中的最后一个关键点。对每个关键点重复此操作,然后重新定义关键点的迭代顺序。这是因为sortedfor循环开始修改它之前,它完成了对dict的迭代

请尝试以下代码:

people = {'adam': {'distance': 14, 'age': 22, 'height': 1.3}, 'charles': {'distance': 3, 'age': 37, 'height': 1.4}, 'jeff': {'distance': 46, 'age': 42, 'height': 1.6}}
people = dict(sorted(people.items(), key=lambda item: item[1]['distance'], reverse=False))
print(people)

输出:

people = {'charles': {'distance': 3, 'age': 37, 'height': 1.4}, 'adam': {'distance': 14, 'age': 22, 'height': 1.3}, 'jeff': {'distance': 46, 'age': 42, 'height': 1.6}}

只需使用^{}

people = dict(sorted(people.items(), key=lambda x: x[1]['distance']))

people = {k: v for k, v in sorted(people.items(), key=lambda x: x[1]['distance'])}

相关问题 更多 >