[英]How to sort values of a dictionary?
I want to sort only VALUES of a dictionary but not KEYS . 我只想对字典的VALUES排序,而不对KEYS排序。 I have reversed the dictionary, so that's not an issue.
我把字典翻过来了,所以这不是问题。 I just want values to be sorted.
我只想对值进行排序。 Following is the code I've tried:
以下是我尝试过的代码:
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)
The output I got is: 我得到的输出是:
{'keen': ['talented'], 'precise': ['exact', 'accurate'],
'exact': ['accurate'], 'bright': ['talented', 'smart'],
'clever': ['smart', 'astute'], 'talented': ['smart', 'astute'],
'smart': ['talented', 'astute']}
The VALUES are not sorted in the output. VALUES 未在输出中排序 。 Please help.
请帮忙。
You are returning the dictionary at the first loop iteration: 您将在第一次循环迭代时返回字典:
for key, value in newdict.items():
newdict[key] = sorted(value)
return newdict
Instead, you could just return new dictionary using dictionary comprehension: 相反,您可以使用字典理解功能返回新字典:
return {k: sorted(v) for k, v in newdict.items()}
You are returning out of your second for loop to 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.