4

I have 3 numpy arrays :

a = numpy.array([['x','y']])
b = numpy.array([['x1','y1']])
c = numpy.array([['x2','y2']])

I want to create a dictionary as:

d={'x': ['x1','x2'], 'y':['y1','y2']}

How do I create such a dictionary?

2
  • 5
    Don't you mean d={'x':['x1','x2'],'y':['y1','y2']} (x2, not y1)? Commented Apr 4, 2017 at 13:29
  • 1
    OP, please edit your question and fix the output or leave a comment clarifying if this is indeed the wanted output (which seems very unlikely). Commented Apr 4, 2017 at 14:44

5 Answers 5

3

If you actually want d={'x':['x1','x2'],'y':['y1','y2']} you can go:

d = {i: [j, x] for i,j,x in zip(a,b,c)}
Sign up to request clarification or add additional context in comments.

1 Comment

You need to unpack a. This leads to a TypeError due to numpy arrays not being hashable.
3

zip the arrays inside a dictionary comprehension:

d = {x: list(*i) for x, i in zip(*a, (b, c))}

or, alternatively:

d = {x: [y, z] for x, (y, z) in zip(*a, (*b, *c))}

or, if you like deep unpacking scenarios:

d = {x: [y, z] for x, ((y, z),) in zip(*a, (b, c))}

there's quite a number of packing/unpacking combinations to choose from. All these of course produce the same output with the dictionary d now being:

{'x': ['x1', 'y1'], 'y': ['x2', 'y2']}

2 Comments

the OP's output d={'x':['x1','y1'],'y':['y1','y2']} (maybe a typo)
@RomanPerekhrest thanks for pointing that out. I err'ed in reading the output; pretty sure that's a typo but I'll wait and see.
1

If you want to preserve your arrays:

print {k: a for k, a in zip(a[0], [b, c])}
>>> {'y': array([['x2', 'y2']], 
  dtype='|S2'), 'x': array([['x1', 'y1']], 
  dtype='|S2')}

Otherwise:

print {k: list(a[0]) for k, a in zip(a[0], [b, c])}
>>> {'y': ['x2', 'y2'], 'x': ['x1', 'y1']}

1 Comment

This is tagged with Python 3 so if you can update your answer to use print as a function. :-)
1

Here is a numpy solution:

import numpy as np

dict(zip(np.ravel(a), np.vstack([b, c]).tolist()))

#{'x': ['x1', 'y1'], 'y': ['x2', 'y2']}

Comments

0

You can try something like this:

d = {k:list(v) for k,v in zip(a,(b,c))}
print(d)

Output:

{'x': ['x1', 'y1'], 'y': ['x2', 'y2']}

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.