0

I need to create a matrix-like structure which can be accessed by its names of the columns and rows.

'''
           Misalign    CPU     Ret
LU_factor   0           6       21
Random      2           10      5
'''

row=["LU_factor","Random"]
col=['Misalign', 'CPU', 'Ret']
Total=[['0', '6', '21'],['2', '10', '5']]

for i in range(0,len(Total)):
    for j in range(0,len(Total[i])):
        print(Total[i][j],end=" ")
        # Matrix[row[i]][col[j]] =Total[i][j]

#print(Matrix)

I do not know what format or data structure I should use to store above data such that I could able to access like:

Matrix["LU_factor"]["CPU"] =6
Matrix["Random"]["Ret"] = 5

I have found one solution through numpy structured array, but I am looking for the solution without using numpy. Thanks in advance.

1 Answer 1

4

You can use dictionaries of dictionaries, something like:

M = {"LU_factor": {'Misalign': 0, 'CPU': 6, 'Ret': 21}, 'Random': {'Misalign': 2, 'CPU': 10, 'Ret': 5}}

should works, you can access or assign values respectively with M["LU_factor"]["CPU"] and M["LU_factor"]["CPU"] = 5.

Specifically you can build the structure you need with a dict comprehension, using your example:

row=["LU_factor","Random"]
col=['Misalign', 'CPU', 'Ret']
Total=[['0', '6', '21'],['2', '10', '5']]

M = {r:{c:Total[k][i] for i, c in enumerate(col)} for k, r in enumerate(row)}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.