I have a dictionary like this:
{device1 : (news1, news2, ...), device2 : (news 2, news 4, ...)...}
How to convert them into a 2-D 0-1 matrix in python? Looks like this:
news1 news2 news3 news4
device1 1 1 0 0
device2 0 1 0 1
device3 1 0 0 1
Here is some code that will create a matrix (or 2D array) using the numpy package. Note that we have to use a list of the names in order because dictionaries do not necessarily store the keys/values in the order they are entered.
import numpy as npdataDict = {'device1':(1,1,0,1), 'device2':(0,1,0,1), 'device3':(1,0,0,1)}
orderedNames = ['device1','device2','device3']dataMatrix = np.array([dataDict[i] for i in orderedNames])print dataMatrix
The output is:
[[1 1 0 1][0 1 0 1][1 0 0 1]]