Creating dictionaries from arrays in Python

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 like:

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

How to create such a dictionary?

+5
source share
5 answers

zip arrays inside dictionary understanding:

 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 scripts:

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

There are quite a few packaging / unpacking combinations to choose from. All this, of course, produces the same conclusion with the dictionary d , which now:

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

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

 d = {i: [j, x] for i,j,x in zip(a,b,c)} 
+3
source

If you want to keep 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
source

Here is the numpy solution:

 import numpy as np dict(zip(np.ravel(a), np.vstack([b, c]).tolist())) #{'x': ['x1', 'y1'], 'y': ['x2', 'y2']} 
+1
source

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']} 
0
source

Source: https://habr.com/ru/post/1266311/


All Articles