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

标签 python dictionary

这个 Python 代码能否被缩短并且仍然可以使用 itertools 和 set 读取?

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 方法:

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

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

关于python - 创建或附加到字典中的列表 - 可以缩短吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4143698/

相关文章:

python - pandas_datareader,导入错误 : cannot import name 'urlencode'

python - 以更有吸引力的方式打印字典键

java - 如何迭代对象列表以从中创建新的 Map?

python - 如何在 Python 3.3 中为所有键(在列表中给出)用 None 填充字典

python - NumPy 排序函数返回 None

python - ImportError : libstdc++. so.6: 找不到版本 `GLIBCXX_3.4.20'

python - IOError 异常处理的单元测试

python - 升级Docker镜像而无需每次都安装require.txt的每个元素

python递归字典转换为字符串

python - python中的快速数据比较