如何对字典的值进行排序?

2024-04-23 13:44:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想对字典的值进行排序,而不想对键进行排序。我把字典翻过来了,所以这不是问题。我只想对值进行排序。以下是我尝试过的代码:

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']}

在输出中未排序。请帮忙。你知道吗


Tags: keyinfor字典排序valuesmartexact
2条回答

你已经从第二个for循环中回到了early

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)

您将在第一次循环迭代时返回字典:

for key, value in newdict.items():
    newdict[key] = sorted(value)
    return newdict

相反,您可以使用字典理解返回新字典:

return {k: sorted(v) for k, v in newdict.items()}

相关问题 更多 >