Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
72 views
in Technique[技术] by (71.8m points)

python - Dictionary Keys into a Matrix

I need a little help with a small task.

I have a dictionary with a tuple of integers (e.g. (1,1), (0,2), etc.)

I want to be able to put this in a matrix that looks like this...

(0,0) | (0,1)  | (0,n)
______|________|_______
(1,0) | (1,1)  | (1,n)
______|________|_______
(m,0) | (m,1)  | (m,n)

Here is a code that I thought would help me append each value on the matrix with the keys in my dictionary.

import numpy as np

rows = 3
columns = 4

my_dict = {}
for i in range(rows):
    for j in range(columns):
        my_dict[i,j] = []

A = np.arange(rows*columns).reshape([rows,columns])
for keys in my_dict.keys():
    for i in range(rows):
        for j in range(columns):
            A[i,j] = my_dict[keys]

I get the following error. ValueError: setting an array element with a sequence.

I believe I am getting this error because it is assigning the key's value, respectfully, which is an empty list. This isn't my intention. I want to associate each element in the matrix with keys associated with my dictionary.

Edit: The desired output should be the following...

(0,0) | (0,1)  | (0,2) | (0,3)  |
______|________|_______|________|
(1,0) | (1,1)  | (1,2) | (1,3)  | = A
______|________|_______|________|
(2,0) | (2,1)  | (2,2) | (2,3)  |
______|________|_______|________|
question from:https://stackoverflow.com/questions/65713481/dictionary-keys-into-a-matrix

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm not sure on your intention but it's just a wrong type which A represented an array of integer but your dictionary value giving a list type. So give its type to list would solve your error basically, but I am also hard to understand what practice in this case

np.arange(rows*columns, dtype = list).reshape([rows,columns])

Full

import numpy as np

rows = 3
columns = 4

my_dict = {}
for i in range(rows):
    for j in range(columns):
        my_dict[i,j] = []

A = np.arange(rows*columns, dtype = list).reshape([rows,columns])
for keys in my_dict.keys():
    for i in range(rows):
        for j in range(columns):
            A[i,j] = my_dict[keys]

Your A

enter image description here

---- Update from new editing issue

import numpy as np

rows = 3
columns = 4

my_dict = {}
for i in range(rows):
    for j in range(columns):
        my_dict[i,j] = []

A = np.arange(rows*columns, dtype = list).reshape([rows,columns])
for keys in my_dict.keys():
    A[keys[0], keys[1]] = keys

Result of A:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...