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

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 get all keys from nested dictionary 
Python :: print colored text in python 
Python :: python pillow convert jpg to png 
Python :: convert plt image to numpy 
Python :: how to use input in python 
Python :: python is dict 
Python :: add tensorflow to conda 
Python :: closing a file in python 
Python :: django serializer 
Python :: tree to tuple python 
Python :: select pandas by t dtype python 
Python :: how to get any letter of a string python 
Python :: extract name of file from path python 
Python :: how to use dictionaries in python 
Python :: plotting confusion matrix 
Python :: sample logistic regression parameters for gridsearchcv 
Python :: add column to df from another df 
Python :: df to sql mysql 
Python :: django get fields data from object model 
Python :: python dictionary to list 
Python :: c++ call python function 
Python :: list to dict python with same values 
Python :: python file to array 
Python :: Fill data in dataframe in pandas for loop 
Python :: what is a slug 
Python :: how to install docx in python 
Python :: pd.get_dummies 
Python :: numpy get diagonal matrix from matrix 
Python :: read and write to file python 
Python :: extract DATE from pandas 
ADD CONTENT
Topic
Content
Source link
Name
1+9 =