创建或附加到字典中的列表 - 可以缩短吗? [英] Create or append to a list in a dictionary - can this be shortened?

查看:98
本文介绍了创建或附加到字典中的列表 - 可以缩短吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用itertools和set来缩短这个Python代码的可读性吗?

Can this Python code be shortened and still be readable using itertools and 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)])


推荐答案

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

An alternative to defaultdict is to use the setdefault method of standard dictionaries:

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

这取决于列表是可变的,所以从setdefault返回的是与字典中相同的列表,因此你可以附加它。

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.

这篇关于创建或附加到字典中的列表 - 可以缩短吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆