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)])
Method 5: Adding a list directly to a dictionary. You can convert a list into a value for a key in a python dictionary using dict() function.
append() adds a list inside of a list. Lists are objects, and when you use . append() to add another list into a list, the new items will be added as a single object (item).
By using ” + ” operator we can append the lists of each key inside a dictionary in Python. After writing the above code (Python append to the lists of each key inside a dictionary), Ones you will print “myvalue” then the output will appear as a “ {'Akash': [1, 3], 'Bharat': [4, 6]} ”.
The Python dictionary offers an update() method that allows us to append a dictionary to another dictionary. The update() method automatically overwrites the values of any existing keys with the new ones.
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.
You can use a defaultdict(list)
.
from collections import defaultdict result = defaultdict(list) for widget_type, app in widgets: result[widget_type].append(app)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With