1

I have a dictionary like this:

 import array as ar
 import numpy as np
 dict = {}
 for i in range(3): dict[i]=ar.array('I')
 dict[0]=np.array([1,2,3], dtype='int')
 dict[1]=np.array([], dtype='int')
 dict[2]=np.array([7,5], dtype='int')

And the dictionary is basically like this:

 0: 1,2,3
 1: []
 2: 7,5

And I want to get an output array like this:

 array([[0,0,0,2,2],[1,2,3,7,5]])

So the first row is the keys in the dictionary, and the second row is the corresponding items in the dictionary. If the items are empty, then remove the keys in the output array. How to generate the array from the input dict in python?

1
  • 1
    @Vishnudev I have in fact a function that its input is basically a key, and output is an array which length may vary. I run the function in a for loop (loop over the key), so to create the dictionary. Do I answer your question? Commented Oct 26, 2020 at 10:43

3 Answers 3

1

Slight modification on your answer:

Change res = np.vstack((aa, bb)) into res = np.array((aa, bb), dtype=int).

import array as ar
import numpy as np

#dict = {}

# why so difficult?

#for i in range(3):
#    dict[i]=ar.array('I')
#dict[0]=np.array([1,2,3], dtype='int')
#dict[1]=np.array([], dtype='int')
#dict[2]=np.array([7,5], dtype='int')

dict = {0: [1,2,3],
        1: [],
        2: [7,5]}

print(dict)

aa = np.hstack([[k]*len(v) for k,v in dict.items()])
bb = np.hstack([v for k,v in dict.items()])
res = np.array((aa, bb), dtype=int)

print(res)

If required for testing you can always add a dot for floating point dtype as per... if you print the dict:

dict = {0: [1,2,3.], # here 3. is float
        1: [],
        2: [7,5]}

The final result is "int" dtype array anyway.

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

Comments

1

I have a for-loop version:

aa = np.hstack([[k]*len(v) for k,v in dict.items()])
bb = np.hstack([v for k,v in dict.items()])
res = np.vstack((aa, bb))

But it somehow changes the dtype to float64. I am looking for a better solution.

Comments

0

Solution with for loops:

keys = []
values = []
for k, v in dict.items():
    for i in v:
        keys += [k]
        values += [i]
result = array([keys, values])

Solution without for loops:

w = [[[k]*len(v), v] for k, v in dict.items()]
result = array([[y for x in [q[0] for q in w] for y in x], [y for x in [q[1] for q in w] for y in x]])

4 Comments

Is there a way to get rid of the for-loops?
@ZF007 I will remove the questions as the author deleted his answers.
first question of you here should be maintained. Otherwise second part of answer doesn't make sense.
I did not delete my answers, somebody or something else did!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.