1

I have two arrays, for example:

a = [a, b, c, d, e, f, g]
b = [1, 2, 3, 4, 5, 6, 7]

My first array is then splitted in a dictionary, in the following form:

dict = {key1: [a, c, e], key2: [f, g], key3: [b, d]}

I would like to get another dictionary, having the same partition but with the elements of array b:

dict = {key1: [1, 3, 5], key2: [6, 7], key3: [2, 4]}

In other words, I would like a correspondence between arrays a and b

2 Answers 2

2

The brute force way to do this is to use index() to look up the index of each element in the sublists of the dict and use that index to lookup the value in b.

You can do that in a single dict comprehension with something like:

a = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
b = [1, 2, 3, 4, 5, 6, 7]

d = {'key1': ['a', 'c', 'e'], 'key2': ['f', 'g'], 'key3': ['b', 'd']}

{k: [b[a.index(l)] for l in v] for k, v in d.items()}
# {'key1': [1, 3, 5], 'key2': [6, 7], 'key3': [2, 4]}

You could make things a little more efficient by creating a lookup dict that maps letters to the indices of a so you don't need to iterate a the index each time with

a_lookup = {l: i for i, l in enumerate(a)}
# then: 
{k: [b[a_lookup[l]] for l in v] for k, v in d.items()}
Sign up to request clarification or add additional context in comments.

Comments

1

Using index and list comprehension:

a = [a, b, c, d, e, f, g]
b = [1, 2, 3, 4, 5, 6, 7]
dict1 = {key1: [a, c, e], key2: [f, g], key3: [b, d]}
dict2 = {}
for key in dict1:
    dict2[key] = [b[a.index(i)] for i in dict1[key]]

How this works:

  1. loop through dict1
  2. Create a dictionary key of that same name in dict2
  3. For each value in that array, set the corresponding values of b as of that in a

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.