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

PythonDictionary

Python Problem Overview


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)

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)])

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

You can use a defaultdict(list).

from collections import defaultdict

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

Solution 3 - Python

may be a bit slow but works

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionculebrónView Question on Stackoverflow
Solution 1 - PythonDaniel RosemanView Answer on Stackoverflow
Solution 2 - PythonMark ByersView Answer on Stackoverflow
Solution 3 - Pythonuser1139002View Answer on Stackoverflow