【问题标题】:How to sort dictionary with string and int value by int only [closed]如何仅通过 int 对字符串和 int 值的字典进行排序 [关闭]
【发布时间】:2021-12-05 16:58:11
【问题描述】:

例如来自字典

{"Name": "Mark","country": "England", "Age":15,

"Name": "Tom","country": "Poland", "Age":10,

"Name": "Sam","country": "USA", "Age":19,

"Name": "Bob","country": "Italy", "Age":17}

我想得到

{"Name": "Tom","country": "Poland", "Age":10,

"Name": "Mark","country": "England", "Age":15,

"Name": "Bob","country": "Italy", "Age":17,

"Name": "Sam","country": "USA", "Age":19,}

这样的代码没有帮助

for key, value in sorted(dict.items(), key=lambda item: int(item[0]))

【问题讨论】:

  • 这不是有效的 Python,或者至少不是你所期望的
  • 您的示例不是字典,因为我们看到重复的键
  • @steve 你的意思是有一个字典列表吗?
  • 排序条件是什么 - 我假设是按年龄计算的,对吧?
  • 这能解决你的问题吗:stackoverflow.com/questions/72899/…

标签: python sorting dictionary


【解决方案1】:

假设你想要一个这样的字典列表:

a = [{"Name": "Tom","country": "Poland", "Age":10},
     {"Name": "Mark","country": "England", "Age":15},
     {"Name": "Bob","country": "Italy", "Age":17},
     {"Name": "Sam","country": "USA", "Age":19}]

这个数据集最明显的答案是:

sorted(a, key=lambda x:x["Age"])

对于对 all 整数值进行排序的更一般的情况,您可以使用类似以下内容:

sorted(a, key=lambda x: sum(v for v in x.values() if isinstance(v, int)))

尽管根据您的用例检查int 可能过于狭窄。该解决方案首先对 dict (v for v in x.values() if isinstance(v, int)) 中的所有整数求和,然后对该总和进行排序。

【讨论】:

    猜你喜欢
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多