pythonlistdictionarylist-comprehension

Trying to get dict[k] from a dict in a list of dicts for k in list or string


I have a couple dictionaries with differing values for the same keys. I have a list of these dicts and I want to return the values from only 1 of the dicts based on the matched keys inside a different list or string. I want it to reflect the dict with a matching list index as the first str in the other list.

group1 = {'1': [0, 0], '2': [2, 2], '3': [3, 3], '4': [4, 4], '5': [5, 5]}
group2 = {'1': [2, 2], '2': [0, 0], '3': [4, 4], '4': [5, 5], '5': [6, 6]}
group3 = {'1': [3, 3], '2': [4, 4], '3': [0, 0], '4': [6, 6], '5': [7, 7]}

group_selection = [group1, group2, group3]

example = ['2', '5', '3', '3', '1', '2']

groups_assigned = [group_selection[k] for k in example]
print(groups_assigned)
# Desired goal is [[0, 0], [6, 6], [4, 4], [4, 4], [2, 2], [0, 0]]   

So far the only way that has worked is

result = [groups_assigned[1][k] for k in example]

I want to be select through the list of dicts to get the correct dict. For the first value in list being '2' it should return the group2 dict values for all remaining string values in list from rest of keys in that dict. '1' would relate to group1, '2' would relate to group2 for as reference

['1', '2', '4', '5'] = [[0, 0], [2, 2], [4, 4], [5, 5]] and ['3', '1'] = [[0,0], [3, 3]]


Solution

  • this should do

    result = [group_selection[int(example[0])-1][x] for x in example]