繁体   English   中英

字典中列表值的排序不起作用 - python

[英]Sorting of list values in dict not working - python

我正在对字典进行排序,它是基于键而不是值进行排序。 如果我尝试使用值进行排序,我会收到错误消息“'<' 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)

这是 output

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

但这里的问题是,它没有对存在的列表值进行排序。 预期的 output 是

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

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

您可以使用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']}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM