【问题标题】:How do i sort a dictionary by a 'subkey' in Python如何在 Python 中按“子键”对字典进行排序
【发布时间】:2021-07-20 16:47:04
【问题描述】:

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

变量

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}}

【问题讨论】:

标签: python sorting dictionary


【解决方案1】:

大多数答案都提供了一种基于旧内容创建字典的方法。如果你想简单地重新排序现有字典的键,你可以做类似的事情:

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

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

【讨论】:

  • 嗯。 @chepner 这真的很有趣!谢谢!与我猜想的公认答案相比,空间与时间的考虑将在这一点上发挥作用。我不能说哪种解决方案更好(与公认的相比),所以我会让其他人参与进来,尽管两者都可以解决我的问题。
  • 时间应该是可比的。内存使用可能是可比的。主要区别在于,例如,如果您希望将 dict 传递给函数并在函数返回后对其进行排序,例如 inplace_dict_sort(d)
【解决方案2】:

只需使用sorted()

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'])}

【讨论】:

    【解决方案3】:

    试试下面的代码:

    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}}
    

    【讨论】:

    • 非常感谢@Pranta,这与我刚刚接受的答案一致。
    猜你喜欢
    • 2011-06-06
    • 2014-04-11
    • 2015-11-03
    • 1970-01-01
    • 2012-02-18
    • 2021-06-28
    • 1970-01-01
    相关资源
    最近更新 更多