在字典中创建/附加到列表值的更好方法

时间:2019-07-17 01:11:41

标签: python python-3.x list dictionary

在下面的程序中,我试图将字典转换为其他字典。

考虑输入字典,该字典的 key 是文件名,而 value 是作者名:

{'1.txt': 'Author1', '2.txt': 'Author1', '3.txt': 'Author2'}

预期输出是一个字典,其 key 是作者名,而 value 是文件列表

{'Author1': ['1.txt', '2.txt'], 'Author2': ['3.txt']}

以下程序可以实现此目标:

def group_by_authors(files):
    grp={}
    for fname, author in files.items():
        if author in grp:
            # if key exists, append to the value
            grp[author].append(fname)
        else:
            # if key does not exist, create a LIST value
            grp[author] = [fname]
    print(grp)

files = {
    '1.txt': 'Author1',
    '2.txt': 'Author1',
    '3.txt': 'Author2'
}

print(files)
group_by_authors(files)

但是我想知道我是否可以避免使用'if-else'语句,而直接对列表值(如果键不存在,则对空列表)进行'append'(或类似操作)。

def group_by_authors(files):
    grp={}
    for fname, author in files.items():
            #single statement to set value of grp[author]
    print(grp)

以下确实实现了转换:

def group_by_authors(files):
    grp = defaultdict(list)
    for fname, author in files:
        grp[author].append(fname)
    print(grp)

但就我而言,我试图在不使用defaultdict的情况下实现它。

1 个答案:

答案 0 :(得分:1)

使用collections.defaultdict

from collections import defaultdict
out = defaultdict(list)
m = {'1.txt': 'Author1', '2.txt': 'Author1', '3.txt': 'Author2'}
for k, v in m.items():
    out[v] += [k]

print(dict(out))
#prints {'Author1': ['1.txt', '2.txt'], 'Author2': ['3.txt']}
相关问题