![](/img/trans.png)
[英]Is there a better way to create a dictionary with key and value from a list of dictionaries dynamically?
[英]Better way to create/append to a list value in a dictionary
在下面的程序中,我试图将字典转换为其他字典。
考虑输入字典,其关键字为文件名, 值为作者名:
{'1.txt': 'Author1', '2.txt': 'Author1', '3.txt': 'Author2'}
预期的输出是一个字典,其关键字是作者名, 值是一个文件列表
{'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的情况下实现它。
使用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']}
defaultdict
确实是最直接的解决方案,但是您可以不这样做而使用dict.setdefault
来代替:
grp = {}
for file, author in files.items():
grp.setdefault(author, []).append(file)
defaultdict
的唯一区别是:a)调用比简单的grp[author]
更为冗长,并且b)即使没有使用,也会在每个调用上创建[]
列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.