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

时间:2010-11-10 10:55:11

标签: python dictionary

这个Python代码是否可以缩短,并且仍然可以使用itertools和sets进行读取?

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

我只能想到这个:

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

3 个答案:

答案 0 :(得分:85)

defaultdict的替代方法是使用标准词典的setdefault方法:

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

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

答案 1 :(得分:47)

您可以使用defaultdict(list)

from collections import defaultdict

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

答案 2 :(得分:4)

可能有点慢,但有效

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