BetterCallMe
BetterCallMe

Reputation: 768

make a dictionary from two arrays such that values of first array shows indices of second array

I have two arrays:

a = array([0,    5,   10,   14, 20])
b = array([42, 41, 11, 22, 33, 10, 22,  2, 45,  3,  9, 10,  1,  3, 45,  1,  4, 2,  9,  8])

Values of a are indices of b and I want to map a and b as a dictionary whose keys are indices of a and values are from b. First key of dictionary takes first 5 values of b , and second key takes next 5 values, third key takes next 4 values and fourth key takes next 6 values and this is inferred by subtracting two consecutive values of a.

Output should be like:

dict = {0: [42, 41, 11, 22, 33],
        1: [10, 22,  2, 45,  3] , 
        2: [9, 10,  1,  3], 
        3: [45,  1,  4, 2,  9,  8]}

The actual size of a and b is in thousands.

Upvotes: 0

Views: 212

Answers (5)

Ghaith Ahmed
Ghaith Ahmed

Reputation: 1

you can use this for your status

a = [0,    5,   10,   14]
b = [42, 41, 11, 22, 33, 10, 22,  2, 45,  3,  9, 10,  1,  3, 45,  1,  4, 2,  9,  8]
dict={}
/* num : Number of values in one key */
num=5
/* x: its for loop */
x=0
list=[]
for i in a:
    # check len of b to handle error out of list
    if x==len(b):
        break
    while x < num+1:
        list.append(b[x])
        dict[i]=list
        x = x + 1
        if num == x:
            num = num + 5
            list=[]
            break
print(dict)

Upvotes: 0

Udipta kumar Dass
Udipta kumar Dass

Reputation: 151

You can use the below code

a = [0, 5, 10, 14, 20]
b = [42, 41, 11, 22, 33, 10, 22,  2, 45,  3,  9, 10,  1,  3, 45,  1,  4, 2,  9,  8]
dictn = {}
for i in range(len(a)-1):
    dictn[i] = b[a[i]:a[i+1]]

Upvotes: 1

Eshaan Gupta
Eshaan Gupta

Reputation: 614

a =[0,    5,   10,   14, 20]
b = [42, 41, 11, 22, 33, 10, 22,  2, 45,  3,  9, 10,  1,  3, 45,  1,  4, 2,  9,  8]

d = {}

for i in range(len(a)-1):
    x = []
    for j in range(a[i+1] - a[i]):
        x.append(b.pop(0))
    d[int(i)] = x
print(d)

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195438

Another solution, using numpy.array_split (I see you're using array()):

x = {i: v for i, v in enumerate(np.array_split(b, a)[1:-1])}
print(x)

Prints:

{0: array([42, 41, 11, 22, 33]), 
 1: array([10, 22,  2, 45,  3]), 
 2: array([ 9, 10,  1,  3]), 
 3: array([45,  1,  4,  2,  9,  8])}

Upvotes: 1

oskros
oskros

Reputation: 3285

You could solve this by a dictionary comprehension, looping over the a list, indexing the b list by the values in a

a = [0,  5,   10,   14, 20]
b = [42, 41, 11, 22, 33, 10, 22,  2, 45,  3,  9, 10,  1,  3, 45,  1,  4, 2,  9,  8]

dct = {i: b[a[i]:a[i+1]] for i in range(len(a)-1)}

Upvotes: 5

Related Questions