5

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)}
2
  • Does the solution have to be scalable? Commented Nov 12, 2017 at 19:06
  • Yes, it has to be. Commented Nov 12, 2017 at 19:08

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It returns an error saying - TypeError: unhashable type: 'numpy.ndarray'
Oh right, I didn't notice the exact form of your a. I assume what you meant there was a = np.array([[1],[3]]). If that's the case, dict(zip(a[:,0], b)) should do it.
2

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]

2 Comments

Still gives an error TypeError: unhashable type: 'numpy.ndarray'
Am sorry, works perfect !! I made an error typing your code.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.