预期产出:
{'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']})
请帮助我使用适当的“sort语句”以获得上述输出
编辑: 我意识到你想要每个数组按字母顺序排列。要解决这个问题,您可以迭代对象上的每个键,然后使用
sort
方法对每个数组进行排序您只需添加一个新行,在每次操作后对数组进行排序:
现在的完整代码是:
旧答案
返回的对象的类型为
defaultdict
。您需要将defaultdict
更改回标准dict
。返回owners
时,将对象强制转换为dict
。例如:所以整个代码现在是这样的:
相关问题 更多 >
编程相关推荐