0

Below there is my dictionary whose keys are 1,2,3. Each key has multiple values. I tried the following code to convert my dictionary to a numpy array but it is not working. Honestly, I don't know about formats so I just have 'i4' and 'f4' which I saw online. Please help.

My_data = {1: [1450.0, -80.0, 840.0, -220.0, 630.0, 780.0, -1140.0], 2: [1450.0, -80.0, 840.0, -220.0, 630.0, 780.0, -1140.0, 450.0, 730.0, -810.0, 390.0, -220.0, -1640.0, -590.0, -145.0, -420.0, 620.0, 450.0, -90.0, 990.0, -705],3:[ 720.0, -230.0, 460.0, 220.0, 710.0, -460.0, 90.0, -640.0, 870.0, -290.0, -2180.0, -790.0, 65.0, 70.0, 460.0] }

names = ['Abc','PL']
formats = ['i4','f4']
dtype = dict(names = names, formats=formats)
my_array = numpy.array(My_data.items(),dtype)
A.S
  • 305
  • 1
  • 4
  • 20
  • 1
    Possible duplicate of [python dict to numpy structured array](https://stackoverflow.com/questions/15579649/python-dict-to-numpy-structured-array) – mech Sep 19 '17 at 15:55
  • 1
    What is your expected output? Does `np.array(My_data.values())` work? – Zero Sep 19 '17 at 15:59
  • @mech : I saw that post but I have multiple values for each key while the post you are pointing to has one value for each key. I tried that but I got error message. – A.S Sep 19 '17 at 15:59
  • @ Zero: Thank you. Yes, it works. – A.S Sep 19 '17 at 16:02
  • `np.array` works with lists (of lists). So the key to converting a dictionary is to first create the desired list. If you aren't picky about the using the `keys`, the list created by `.values` is a good start. – hpaulj Sep 19 '17 at 16:29
  • @hpaulj: I do need to use keys. I am going to calculate correlation for these data later and need to refer to keys. – A.S Sep 19 '17 at 16:36
  • Can you use the `keys()` and `values()` in separate arrays? – hpaulj Sep 19 '17 at 16:44

0 Answers0