简体   繁体   中英

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)}

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.

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]

small mistake in c, needs a comma between the two inner lists (are nested lists necessary here?)

Anyways, here is a solution that gives the desired output you want.

import numpy as np
c = {}

a = [[1],[3]]

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

for i in range(len(a)):
    c[a[i][0]] = b[i]

Create a dictionary first (c), then use the values in your nested list a as keys. for each of those keys assign the array in your list b at the same index (i). Do note that this requires that the indexes of a corresponds to the same positions in b.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM