How to Store an Array in a Dictionary Using Python

I am currently attempting to modify a series of programs by utilizing dictionaries as opposed to arrays. I have columns of raw information in a file, which is then read into an ASCII csv file. I need to convert this file into a dictionary, so that it can be fed into another program.

I used a numpy.genfromtxt to pull out the information i need from the csv file, following this format:

a,b,c,d = np.genfromtxt("file",delimiter = ',', unpack = true)

this step works completely fine.

I then attempt to build a dictionary:

ouputDict = dict([a,a],[b,b],[c,c],[d,d])

As i understand it, this should make the key "a" in the dictionary a correspond to the array "a".

thus if:

a = [1,2,3,4]

then:

outputDict[a][0] = 1

However, when i attempt to create this dictionary i receive the following error:

TypeError: unhashable type: 'numpy.ndarray'

Why can't I construct an array in this fashion and what is the workaround, if any? Any help will be greatly appreciated!

7

2 Answers

You can do this even with using collections

Declare your dictionary as:

Dictionary = {}; // {} makes it a key, value pair dictionary

add your value for which you want an array as a key by declaring

Dictionary[a] = [1,2,3,4]; // [] makes it an array

So now your dictionary will look like

{a: [1,2,3,4]}

Which means for key a, you have an array and you can insert data in that which you can access like dictionary[a][0] which will give the value 1 and so on. :)

Btw.. If you look into examples of a dictionary, array and key value pairs, nested dictionary, your concept will get clearer.

2

Copied from my comment:

Correct dictionary formats:

{'a':a, 'b':b,...}, or 
dict(a=a, b=b,...)
dict([('a', a), ('b', b),...])

The goal is to make the strings 'a','b',etc the keys, not the variable values.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest