1

I need help with this,

I have a list of lists and a list of dictionaries. The list of dictionaries has for its values, list of indexes that point to the items in the list of lists. what I need to do is to create a new list of dictionaries from those other two.

list_1 = [[a,b,c], [d,e,f], ...]

list_2 = [{key_11: [0,2] , key_12: [0]}, {key_21: [2,0], key_22: [1]}, ...]

The values of the first dictionary in list_2, point only to the first list o list_1 and so on...

What I need is a new list of dictionaries with the same keys but with values of the items on list_1[i] represented by the values of the dicts on list_2. So something like this:

return [{{key_11: [a,c] , key_12: [a]}, {key_21: [f,d], key_22: [e]}, ...]

I tried something like this:

return [{key: some_funct(val) for key, val in x.items()} for x in list_2]

and some_funct takes a value of the dictionary and returns the correct items on list_1[x] for x in list_2

I know I'm close! but I can't get some_funct to work properly and I think it's because I'm trying to map three things, every element on list_1, every dictionary on list_2 and every value for each dictionary.

1 Answer 1

1

You need to use zip here to iterate through both lists concurrently. Then for every such list, we use dictionary comprehension to map the elements in the list to their counterparts.

Like:

[{k:[sub1[v] for v in vs] for k, vs in sub2.items()}
 for sub1, sub2 in zip(list_1, list_2)]

this produces - with your sample input:

>>> list_1 = [['a','b','c'], ['d','e','f']]
>>> list_2 = [{'key_11': [0,2] , 'key_12': [0]}, {'key_21': [2,0], 'key_22': [1]}]
>>> [{k:[sub1[v] for v in vs] for k, vs in sub2.items()}
...  for sub1, sub2 in zip(list_1, list_2)]
[{'key_12': ['a'], 'key_11': ['a', 'c']}, {'key_21': ['f', 'd'], 'key_22': ['e']}]

How does it work?

The outer part is list comprehension. We iterate over zip(list_1, list_2) so we obtain the rows of list_1 and list_2 so to speak. These rows sub1 and sub2 are a list and a dictionary respectively.

For every such sub1, sub2, we construct a dictionary in the resulting list. This dictionary is constructed with dictionary comprehension {k:[sub1[v] for v in vs] for k, vs in sub2.items()}. We iterate through the key-value tuples in the sub2 (the sub2.items() and for every such key-value pair we associate the key k, with a value that is constructed through list comprehension again, based on the value of the dictionary vs.

vs is thus a list associated with the key in the dictionary, all we have to do is obtain the element that is associated with the index, so we perform a mapping [sub1[v] for v in vs].

Sign up to request clarification or add additional context in comments.

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.