How to convert a dictionary to a matrix or nArray in Python?

How to convert a dictionary to a matrix or nArray in Python?

This recipe helps you convert a dictionary to a matrix or nArray in Python
In [1]:
## How to Convert a Dictionary into a Matrix or nArray
def Kickstarter_Example_5():
    print()
    print(format('How to Convert a Dictionary into a Matrix or ndArray',
                 '*^72'))

    # Load library
    from sklearn.feature_extraction import DictVectorizer

    # Our dictionary of data
    data_dict = [{'Apple': 2, 'Orange': 4},
                 {'Apple': 4, 'Orange': 3},
                 {'Apple': 1, 'Banana': 2},
                 {'Apple': 2, 'Banana': 2}]
    print()
    print(data_dict)

    # Create DictVectorizer object
    dictvectorizer = DictVectorizer(sparse=False)

    # Convert dictionary into feature matrix
    features = dictvectorizer.fit_transform(data_dict)

    # View feature matrix
    print()
    print(features)

    # View feature matrix column names
    dictvectorizer.get_feature_names()

Kickstarter_Example_5()
**********How to Convert a Dictionary into a Matrix or ndArray**********

[{'Apple': 2, 'Orange': 4}, {'Apple': 4, 'Orange': 3}, {'Apple': 1, 'Banana': 2}, {'Apple': 2, 'Banana': 2}]

[[2. 0. 4.]
 [4. 0. 3.]
 [1. 2. 0.]
 [2. 2. 0.]]


Stuck at work?
Can't find the recipe you are looking for. Let us know and we will find an expert to create the recipe for you. Click here
Companies using this Recipe
1 developer from HvH
1 developer from New Delhi DataPoint
1 developer from Altimetrik
1 developer from KPMG
1 developer from Renovite Technologies
1 developer from ANAC
1 developer from LTI
1 developer from Vodafone
1 developer from Fossil Group
1 developer from MudraCircle