Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

from collections import defaultdict

>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
...     d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
Comment

COLLECTIONS.DEFAULTDICT(set)

defaultdict means that if a key is not found in the dictionary,
then instead of a KeyError being thrown, a new entry is created. 
The type of this new entry is given by the argument of defaultdict.

For example:

somedict = {}
print(somedict[3]) # KeyError

someddict = defaultdict(int)
print(someddict[3]) # print int(), thus 0

>>> from collections import defaultdict
Comment

PREVIOUS NEXT
Code Example
Python :: python count elements in sublists 
Python :: django query filter greater than or equal to 
Python :: read variable in a string python 
Python :: conda create new env 
Python :: plt.scatter background color 
Python :: views.py 
Python :: how to check python to see if list length is even 
Python :: standard deviation in python without numpy 
Python :: exception handling in tkinter 
Python :: sorted python 
Python :: python tex box 
Python :: identity matrix with numpy 
Python :: protected class python 
Python :: drop the first 10 values of list python 
Python :: python skip input 
Python :: pandas read parquet from s3 
Python :: print torch model python 
Python :: transpose matrice numpy 
Python :: find location of max value in python list 
Python :: subplots 
Python :: urllib_errors 
Python :: django make app 
Python :: matplot image axis 
Python :: Python re.subn() 
Python :: how to add a 2d array to one dataframe colum 
Python :: find an item in a list python 
Python :: numpy diag() 
Python :: Convert a Pandas Column of Timestamps to Datetimes 
Python :: neat way to print 2d array 
Python :: plot scattered dataframe 
ADD CONTENT
Topic
Content
Source link
Name
9+3 =