Caroline.py Caroline.py - 3 months ago 7
Python Question

Creating a matrix of a certain size from a dictionary

I am wanting to solve a systems of equations through linalg.solve(A, b) Solve a linear matrix equation, or system of linear scalar equations from scipy.org. Specifically, I have two dictionaries, dict1 and dict1, and I need to convert them to matrices in order to use the above script.

food = ['fruits', 'vegetables', 'bread', 'meat']
frequency = ['daily', 'rarely']
consumptions = {'fruits': {'daily': 6, 'rarely': 4}, 'vegetables': {'daily': 8, 'rarely': 6}, 'bread': {'daily': 2, 'rarely': 1}, 'meat': {'daily': 2, 'rarely': 1}}

dict1 = {}
for f in food: #type of food
for j in food:
dict2 = {}
total = 0.
for q in frequency:
dict2.update({q:(consumptions.get(j).get(q)*consumptions.get(f).get(q))})
key = f+'v'+j #comparing the different foods
dict1.update({key:dict2})


This gives me:

{'breadvbread': {'daily': 4, 'rarely': 1},
'breadvfruits': {'daily': 12, 'rarely': 4},
'breadvmeat': {'daily': 4, 'rarely': 1},
'breadvvegetables': {'daily': 16, 'rarely': 6},
'fruitsvbread': {'daily': 12, 'rarely': 4},
'fruitsvfruits': {'daily': 36, 'rarely': 16},
'fruitsvmeat': {'daily': 12, 'rarely': 4},
'fruitsvvegetables': {'daily': 48, 'rarely': 24},
'meatvbread': {'daily': 4, 'rarely': 1},
'meatvfruits': {'daily': 12, 'rarely': 4},
'meatvmeat': {'daily': 4, 'rarely': 1},
'meatvvegetables': {'daily': 16, 'rarely': 6},
'vegetablesvbread': {'daily': 16, 'rarely': 6},
'vegetablesvfruits': {'daily': 48, 'rarely': 24},
'vegetablesvmeat': {'daily': 16, 'rarely': 6},
'vegetablesvvegetables': {'daily': 64, 'rarely': 36}}


I would like to convert this into a 4 x 4 matrix since I am using 4 types of foods. I did not put dict2 as once I figure out how to convert to a matrix with one dictionary, I can do the other but if you need it, I can update.

I am new to Python and wanted to play around with dictionaries and the matrix solver :) . It was easy to do it with arrays, but now I want to see how to go about if I have dictionaries.

Answer

You can create a 4x4x2 numpy array from the dictionary using list comprehension:

import numpy as np

A = np.array([[[consumptions[x]["daily"]*consumptions[y]["daily"],
                  consumptions[x]["rarely"]*consumptions[y]["rarely"]]
                  for y in food]
                  for x in food])

This will give you:

array([[[36, 16],
        [48, 24],
        [12,  4],
        [12,  4]],

       [[48, 24],
        [64, 36],
        [16,  6],
        [16,  6]],

       [[12,  4],
        [16,  6],
        [ 4,  1],
        [ 4,  1]],

       [[12,  4],
        [16,  6],
        [ 4,  1],
        [ 4,  1]]])

Then, to get a 4x4 matrix of the daily values and the rarely values separately, use numpy's advanced slicing:

daily = A[:, :, 0]

array([[36, 48, 12, 12],
       [48, 64, 16, 16],
       [12, 16,  4,  4],
       [12, 16,  4,  4]])

If you want to make the meaning of these values more explicit, you can convert this to a pandas DataFrame:

import pandas as pd

pd.DataFrame(daily, columns=food, index=food)

            fruits  vegetables  bread   meat
fruits      36      48          12      12
vegetables  48      64          16      16
bread       12      16          4       4
meat        12      16          4       4