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

时间:2020-09-05 20:24:10

标签: python dictionary

我有以下字典:

    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

是否有更有效/更优雅的方法?

谢谢

2 个答案:

答案 0 :(得分:1)

选项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)

答案 1 :(得分:1)

这是我的看法。使用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