Python 创建或附加到字典中的列表 - 可以缩短吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4143698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:26:13  来源:igfitidea点击:

Create or append to a list in a dictionary - can this be shortened?

pythondictionary

提问by culebrón

Can this Python code be shortened and still be readable using itertools and sets?

可以使用 itertools 和 set 缩短此 Python 代码并仍然可读吗?

result = {}
for widget_type, app in widgets:
    if widget_type not in result:
        result[widget_type] = []
    result[widget_type].append(app)

I can think of this only:

我只能想到这个:

widget_types = zip(*widgets)[0]
dict([k, [v for w, v in widgets if w == k]) for k in set(widget_types)])

采纳答案by Mark Byers

You can use a defaultdict(list).

您可以使用一个defaultdict(list).

from collections import defaultdict

result = defaultdict(list)
for widget_type, app in widgets:
    result[widget_type].append(app)

回答by Daniel Roseman

An alternative to defaultdictis to use the setdefaultmethod of standard dictionaries:

另一种方法defaultdict是使用setdefault标准词典的方法:

 result = {}
 for widget_type, app in widgets:
     result.setdefault(widget_type, []).append(app)

This relies on the fact that lists are mutable, so what is returned from setdefault is the same list as the one in the dictionary, therefore you can append to it.

这依赖于列表是可变的这一事实,因此从 setdefault 返回的列表与字典中的列表相同,因此您可以附加到它。

回答by user1139002

may be a bit slow but works

可能有点慢但有效

result = {}
for widget_type, app in widgets:
    result[widget_type] = result.get(widget_type, []) + [app]