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:
You can use a defaultdict(list)
.
from collections import defaultdict
result = defaultdict(list)
for widget_type, app in widgets:
result[widget_type].append(app)
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)
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.
may be a bit slow but works
result = {}
for widget_type, app in widgets:
result[widget_type] = result.get(widget_type, []) + [app]