python - 按升序对返回的字典中的值列表进行排序-Python

标签 python list sorting python-3.x dictionary

以下函数返回输入字典的反转,其中原始字典的值用作返回字典的键,原始字典的键用作返回字典的值:

def lower(d):
    return dict((k.lower(), [item.lower() for item in v]) for k, v in d.iteritems())

def reverse_dictionary(input_dict):
    D=lower(input_dict)
    reverse_dict = {}
    for key, value in D.iteritems():
        if not isinstance(value, (list, tuple)):
            value = [value]
        for val in value:
            reverse_dict[val] = reverse_dict.get(val, [])
            reverse_dict[val].append(key)
    for key, value in reverse_dict.iteritems():
        if len(value) == 1:
            reverse_dict[key] = value[0]

    return reverse_dict
input_dict= {'astute': ['Smart', 'clever', 'talented'], 
            'Accurate': ['exact', 'precise'], 
            'exact': ['precise'], 'talented': ['smart', 'keen', 'Bright'], 
            'smart': ['clever', 'bright', 'talented']}
print(reverse_dictionary(input_dict))

但是返回的字典中的值列表未按升序排序。

该函数返回:

{'precise': ['accurate', 'exact'], 'clever': ['astute', 'smart'], 'talented': ['astute', 'smart'], 'keen': 'talented', 'bright': ['talented', 'smart'], 'exact': 'accurate', 'smart': ['astute', 'talented']}

正确的输出是:

{'precise': ['accurate', 'exact'], 'clever': ['astute', 'smart'], 'talented': ['astute', 'smart'], 'keen': ['talented'], 'bright': ['smart', 'talented'], 'exact': ['accurate'], 'smart': ['astute', 'talented']}

任何帮助将不胜感激。

最佳答案

reverse_dict 只是一个普通的旧字典,它保留向其中添加元素的顺序,从而使整个方法有些毫无意义。相反,如果您希望保留插入顺序,则应在初始化时使用 collections 模块中的 OrderedDict (from collections import OrderedDict)变量:

reverse_dict = OrderedDict();

关于python - 按升序对返回的字典中的值列表进行排序-Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35972960/

相关文章:

python - PyGObject 的替代品?

r - 根据名称选择列表元素

python list.iteritems 替换

java - Java中根据索引数组对数组进行排序(类似于C#的Array.Sort())

algorithm - 多标准排序/分配到集合中

python - 如何用数字关键字字典替换纯数字列? [Python]

python - 微调 mnist 深度自动编码器模型

python - 按值获取 numpy 数组中前 k 个数字的索引?

java - 嵌套列表中的通用类型和通配符

arrays - MongoDB:排序数组