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?
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)}
a. This leads to a TypeError due to numpy arrays not being hashable.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']}
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']}
d={'x':['x1','x2'],'y':['y1','y2']}(x2, noty1)?