【问题标题】:Sorting of list values in dict not working - python字典中列表值的排序不起作用 - python
【发布时间】:2022-11-28 13:47:29
【问题描述】:

我正在对字典进行排序,它是基于键而不是值进行排序。如果我尝试使用值进行排序,我会收到错误消息“'<' not supported between instances of 'list' and 'int'”

下面是我使用的代码。

    cars = "ABC/{'Place': 'UK', 'Fruit': 'Apple', 'Vit': ['C','A'], 'Check': ['B', 'C', 'X', 'D','A']}/Place"
    

import re
import ast
y = ast.literal_eval(re.search('({.+})', cars).group(0))
from collections import OrderedDict
new_dict = dict(OrderedDict(sorted(y.items())))
print(new_dict)

这是输出

{
    'Check': ['B', 'C', 'X', 'D', 'A'],
    'Fruit': 'Apple',
    'Place': 'UK',
    'Vit': ['C', 'A']
}

但这里的问题是,它不是对存在的列表值进行排序。 预期的输出是

{       
    'Check': ['A','B','C','D','X'],
    'Fruit': 'Apple',
    'Place': 'UK',
    'Vit': ['A', 'C']
}

所以只要有 list value ,它就应该对该列表进行排序。 谁能帮我这个 。

【问题讨论】:

  • 你打算对字典的键进行排序吗?或者这是一个巧合的错误,你真的只想对列表值进行排序?您显示的所有代码都不会生成您在标题中描述的异常,所以事情有点混乱。
  • 抱歉,我编辑了问题,您可以查看@Blckknght
  • 首先它应该使用 value 然后使用 key 进行排序,我在问题中显示了预期的结果,如果字典中的值是一个列表,我希望它对值进行排序
  • 但是您没有对值进行排序。 sorted(y.items()) 将对键进行排序,OrderedDict 将按排序顺序维护键。你需要做for k in y: / y[k].sort()
  • 我看到了问题。绝对没有您发布的匹配项或任何意义。错误与代码不匹配。出于某种原因,您正在使用 ast 从带有尾随垃圾的字符串中解析 json。当您想对字典值进行排序时,您的排序字典键。这到处都是。,

标签: python dictionary


【解决方案1】:

您可以使用isinstance 来检查一个值是否是列表,然后相应地应用sorted

dct = {
    'Check': ['B', 'C', 'X', 'D', 'A'],
    'Fruit': 'Apple',
    'Place': 'UK',
    'Vit': ['C', 'A']
}

output = {k: sorted(v) if isinstance(v, list) else v for k, v in sorted(dct.items())}

print(output) # {'Check': ['A', 'B', 'C', 'D', 'X'], 'Fruit': 'Apple', 'Place': 'UK', 'Vit': ['A', 'C']}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多