[英]How to sort values of a dictionary?
我只想对字典的VALUES排序,而不对KEYS排序。 我把字典翻过来了,所以这不是问题。 我只想对值进行排序。 以下是我尝试过的代码:
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']}
VALUES 未在输出中排序 。 请帮忙。
您将在第一次循环迭代时返回字典:
for key, value in newdict.items():
newdict[key] = sorted(value)
return newdict
相反,您可以使用字典理解功能返回新字典:
return {k: sorted(v) for k, v in newdict.items()}
您正从第二个循环返回到早期
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.