Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)]) 
like image 941
culebrón Avatar asked Nov 10 '10 10:11

culebrón


People also ask

Can you append a list to a dictionary?

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.

What happens if you append a list to a list?

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

How do you append to a list that is a value in a dictionary Python?

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]} ”.

Can you use append with dictionaries in Python?

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.


2 Answers

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.

like image 157
Daniel Roseman Avatar answered Oct 02 '22 23:10

Daniel Roseman


You can use a defaultdict(list).

from collections import defaultdict  result = defaultdict(list) for widget_type, app in widgets:     result[widget_type].append(app) 
like image 30
Mark Byers Avatar answered Oct 03 '22 00:10

Mark Byers