2

I want to remove the outer list from dictionary values but I can only find the unpacking method not sure how to use this on dictionary values.

My data looks like this:

{'A': array([[ 1.90769404e-01,  1.26112014e-01, -2.17013955e-02]],
 'B': array([[ 2.80194253e-01,  1.19333006e-01,  3.63824964e-02]],
 'C': array([[ 1.40285566e-01,  4.76801395e-02,  5.49828596e-02]]}

I want to remove the outer lists to make them like this:

{'A': array([ 1.90769404e-01,  1.26112014e-01, -2.17013955e-02],
 'B': array([ 2.80194253e-01,  1.19333006e-01,  3.63824964e-02],
 'C': array([ 1.40285566e-01,  4.76801395e-02,  5.49828596e-02]}

How can I do this?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Osca
  • 1,588
  • 2
  • 20
  • 41
  • @CSMaverick Please do not self-advertise here, that reaallllllly irritates users, (and me), This is a bad attitude ))) – U13-Forward Sep 09 '18 at 00:01

2 Answers2

1

Of course use indexing:

>>> {k:v[0] for k,v in DIC.items()}
{'A': array([ 0.1907694 ,  0.12611201, -0.0217014 ]), 'B': array([ 0.28019425,  0.11933301,  0.0363825 ]), 'C': array([ 0.14028557,  0.04768014,  0.05498286])}
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • Of course I will. I got little problem here, after removing the outer list, I want to reshape the dictionary values to 2D by using `for i, value in DIC.items(): DIC[i] = value.reshape(1, -1)` However, the value went back to two nested list, is there any better way to reshape it to avoid this ? thanks – Osca Sep 06 '18 at 06:02
  • 1
    That reshape makes no sense. If you want to have a 2D array with one row, you'll end up with those nested brackets. – Mad Physicist Sep 06 '18 at 06:49
  • @MadPhysicist Thanks for letting me know, (i don't know numpy) – U13-Forward Sep 06 '18 at 06:49
  • @CSMaverick takkyi83's second comment says "of course i will", so why not – U13-Forward Sep 06 '18 at 22:40
  • @CSMaverick is because he said something about reshaping so i deleted it because, maybe it's not what he want's, Btw, my answer is already accepted, why still? – U13-Forward Sep 08 '18 at 23:53
  • @CSMaverick Stop these questions, this irritates me (a lot) – U13-Forward Sep 09 '18 at 00:04
0

Python dictionaries solution:

{i:j[0] for i,j in DICTIONARY.items() }

#  
  {'A': [0.190769404, 0.126112014, -0.0217013955],
   'B': [0.280194253, 0.119333006, 0.0363824964],
   'C': [0.140285566, 0.0476801395, 0.0549828596]}

Python Numpy Array's solution

arr = {'A': np.array([[ 1.90769404e-01,  1.26112014e-01, -2.17013955e-02]]),
       'B': np.array([[ 2.80194253e-01,  1.19333006e-01,  3.63824964e-02]]),
       'C': np.array([[ 1.40285566e-01,  4.76801395e-02,  5.49828596e-02]])}


print({k:v[0].ravel() for k,v in arr.items()})

output

{'A': array([ 0.1907694 ,  0.12611201, -0.0217014 ]), 'B': array([0.28019425, 0.11933301, 0.0363825 ]), 'C': array([0.14028557, 0.04768014, 0.05498286])}
Chandu
  • 2,053
  • 3
  • 25
  • 39