Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a Numpy Array to a dictionary

How to add two numpy arrays to a dictionary in python ?

a = [[1]
     [3]]

b = [array([[[ 41.,  179.],
             [ 451.,  254.],
             [ 449.,  10.],
             [ 53.,  256.]]], dtype=float32), array([[[ 181.,  313.],
             [  27.,  24.],
             [ 113.,  192.],
             [ 08.,  20.]]], dtype=float32)]

I wish to display a and b as

c = {1: array([[ 41.,  179.],
            [ 451.,  254.],
            [ 449.,  10.],
            [ 53.,  256.]], dtype=float32),
     3: array([[ 181.,  313.],
           [  27.,  24.],
           [ 113.,  192.],
           [ 08.,  20.]], dtype=float32)}
like image 596
vulcanrs Avatar asked Nov 12 '17 18:11

vulcanrs


2 Answers

c = dict(zip(a[:,0], b)) would turn your a and b variables into a dictionary. I'm not sure whether that's what you're looking for, though.

like image 166
Dominik Stańczak Avatar answered Oct 09 '22 17:10

Dominik Stańczak


Using a dictionary comprehension:

I assume you meant to define a as:

a = [1, 3]

then you can get c with:

c = {e: b[i] for i, e in enumerate(a)}

which gives the intended output of:

{1: array([[[  41.,  179.],
    [ 451.,  254.],
    [ 449.,   10.],
    [  53.,  256.]]], dtype=float32),
 3: array([[[ 181.,  313.],
    [  27.,   24.],
    [ 113.,  192.],
    [   8.,   20.]]], dtype=float32)}

If you actually only have a as a list of an element as in [[1], [3]], you can do:

a = [i[0] for i in a]
#[[1], [3]] --> [1, 3]
like image 22
Joe Iddon Avatar answered Oct 09 '22 18:10

Joe Iddon