python - 如何仅通过 int 对字符串和 int 值的字典进行排序
问题描述
例如从字典
{"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]))
解决方案
假设你打算有一个这样的字典列表:
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"])
对于对所有整数值进行排序的更一般情况,您可以使用以下内容:
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))
,然后对该总和进行排序。