【发布时间】:2021-10-13 11:09:42
【问题描述】:
预期输出:
{'Albert': ['btech.txt', 'Input.txt', 'Output.txt'], 'Stanley': ['Code.py']}
from collections import defaultdict
def groupAndSortOwners(files):
owners = defaultdict(list)
for file, owner in files.items():
owners[owner].append(file)
return owners
files = {
'Input.txt': 'Albert',
'Code.py': 'Stanley',
'Output.txt': 'Albert',
'btech.txt':'Albert',
}
print(groupAndSortOwners(files))
获取输出为:
defaultdict(<class 'list'>, {'Albert': ['Input.txt', 'Output.txt', 'btech.txt'],
'Stanley': ['Code.py']})
请帮助我使用适当的“排序语句”以获得上述输出。
【问题讨论】:
-
想要对字典元素进行排序
-
如果您只是想对列表进行绝对排序,请使用
sorted()kite.com/python/answers/… -
把最后一行改成
return {k: sorted(v) for k, v in sorted(owners.items())}? -
仍然无法正常工作我希望 btech.txt 在开头
-
当前输出:{'Albert': ['Input.txt', 'Output.txt', 'btech.txt'], 'Stanley': ['Code.py']} 预期输出: {'Albert': ['btech.txt', 'Input.txt', 'Output.txt'], 'Stan': ['Code.py']}
标签: python python-3.x sorting