Reshape dictionary values from 1D to 2D array

Reshape dictionary values from 1D to 2D array



I want to calculate cosine similarity for words in two dictionaries. The words are keys, arrays are values. In order to do this, I need to convert them to 2D array first, I did some research and found x = x.reshape(1,-1)
I successfully converted it with a single value in dictionary, however, I don't know how to convert the whole dictionary's values by using for loops.


x = x.reshape(1,-1)



The data


D
'A': array([ 4.80625004e-01, -1.40245005e-01, -9.99999046e-03]),
'B': array([-0.46553 , -0.1519755 , 0.41836]),
'C': array([0.0090175 , 0.05817001, -0.09712502])

D2 (same format as D)
'D': ([8.11059952e-01, 6.84859991e-01, 1.01619996e-01]),
'E':([-0.82868 , 0.49513 , 0.67581]),
'F':([-0.17093 , 0.88746 , 0.0931135])



I tried


for i in D2.items():
D2[i] = D2[i].reshape(1, -1) #Error on this line



but received error: TypeError: unhashable type: 'numpy.ndarray'



Some advice please? thank you in advanced!





Where/how do you define D2_RESHAPE?
– MoRe
Sep 2 at 8:58



D2_RESHAPE





it's same as D2, sorry i renamed the variable
– Osca
Sep 2 at 9:00




2 Answers
2



Dict.items() returns tuples of the key, value pairs. Therefore in your case i is a tuple of the key and the value. Try:


i


for i, value in D2.items():
D2[i] = value.reshape(1, -1)



try this


from numpy import array

d = dict('A': array([ 4.80625004e-01, -1.40245005e-01, -9.99999046e-03]),
'B': array([-0.46553 , -0.1519755 , 0.41836]),
'C': array([0.0090175 , 0.05817001, -0.09712502]))

reshaped_arrays = dict()
for x, j in d.items():
dd[x]=j.reshape(1,-1)





This returns a list instead of an array and therefore loses the info about the key.
– MoRe
Sep 2 at 9:20



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Some of your past answers have not been well-received, and you're in danger of being blocked from answering.



Please pay close attention to the following guidance:



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế