gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:49:45 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com