我只想对字典的值进行排序,而不想对键进行排序。我把字典翻过来了,所以这不是问题。我只想对值进行排序。以下是我尝试过的代码:
def reverse_dictionary(olddict):
newdict = {}
for key, value in olddict.items():
for string in value:
newdict.setdefault(string.lower(), []).append(key.lower())
for key, value in newdict.items():
newdict[key] = sorted(value)
return newdict
olddict=({'astute': ['Smart', 'clever', 'talented'],
'Accurate': ['exact', 'precise'],
'exact': ['precise'],
'talented': ['smart', 'keen', 'Bright'],
'smart': ['clever', 'bright', 'talented']})
result=reverse_dictionary(olddict)
print(result)
我得到的结果是:
{'keen': ['talented'], 'precise': ['exact', 'accurate'],
'exact': ['accurate'], 'bright': ['talented', 'smart'],
'clever': ['smart', 'astute'], 'talented': ['smart', 'astute'],
'smart': ['talented', 'astute']}
值在输出中未排序。请帮忙。你知道吗
你已经从第二个for循环中回到了early
您将在第一次循环迭代时返回字典:
相反,您可以使用字典理解返回新字典:
相关问题 更多 >
编程相关推荐