有没有更好的方法来重新排列字典值



我有以下字典:

files = {
'Input.txt': 'Randy',
'Code.py': 'Stan',
'Output.txt': 'Randy'}

我想返回一个字典,其中键是名称,对应的值是文件名列表:

{'Randy': ['Input.txt', 'output.txt'], 'Stan': ['Code.py']}

我设法用2个for循环做到了这一点:

def group_by_owners(files):
my_dict = {}
for value in files.values():
if value not in my_dict:
my_dict[value] = []

for key, value in files.items():
if value in my_dict.keys():
my_dict[value].append(key)
return my_dict

有没有一种更有效/更优雅的方法来做到这一点?

感谢

选项1:defaultdict

默认字典具有一个空列表的默认值,因此您可以将值附加到其中。

这种解决方案是优选的。

files = {
'Input.txt': 'Randy',
'Code.py': 'Stan',
'Output.txt': 'Randy'}
from collections import defaultdict
inv_map = defaultdict(list)
{inv_map[v].append(k) for k, v in files.items()}
# {'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']}
print(inv_map)

选项2:字典

files = {
'Input.txt': 'Randy',
'Code.py': 'Stan',
'Output.txt': 'Randy'}
inv_map = {}
for k, v in files.items():
inv_map[v] = inv_map.get(v, []) + [k]
# {'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']}
print(inv_map)

以下是我对此的看法。使用defaultdict来避免创建初始列表,而只使用append

from collections import defaultdict
def group_by_owners(files):
# Creates a dictionary that it's initial value is a list
# therefore you can just start using `append`
result = defaultdict(list)
for key, value in files.items():
result[value].append(key)
return result

最新更新