Carlos Eduardo Corpus
Carlos Eduardo Corpus

Reputation: 349

Matching the keys of a dictionary with a reference list and getting the values

I'm working with a problem with dictionaries and I hit a roadblock, so I have a 3D list with coordinates that I use for reference and a dictionary whose keys match the coordinates in the list, what I need, it's that if the key and the coordinate matches, then, append the value in another 3D list. I know almost how to do it, but I'm not getting what I want, this is what I tried:

reference = [[[2, 3], [2, 4], [3, 2], [4, 2]], 
             [[2, 3], [3, 2], [3, 4], [4, 3]], 
             [[2, 3], [3, 2], [3, 4], [4, 3]]]

mydict = {(2, 3): [5, 1], (2, 4): [14, 16], (3, 2): [19, 1], (3, 4): [14, 30], (4, 2): [16, 9], (4, 3): [6, 2]}

aux = [[tuple(j) for j in i] for i in reference] #This transform the 3D list to tuples to match the keys

print(aux)

aux = [[(2, 3), (2, 4), (3, 2), (4, 2)], [(2, 3), (3, 2), (3, 4), (4, 3)], [(2, 3), (3, 2), (3, 4), (4, 3)]]

aux_list = []
    for key, value in mydict.items():
        final_list =[]
        for i in aux:
            for j in i:                    #If the key matches the list of tuples then append the value
                if j == key:
                    aux_list.append(value)
        final_list.append(aux_list)

print(final_list)

final_list = [[[5, 1], [5, 1], [5, 1], [14, 16], [19, 1], [19, 1], [19, 1], [14, 30], [14, 30], [16, 9], [6, 2], [6, 2]]]

This gave me the correct values, but the order it's a little messed up and although it's a 3D list, the separation it's not like the reference list, this should be my desired output:

final_list = [[[5, 1], [14, 16], [19,  1], [16, 9]],
              [[5, 1], [19,  1], [14, 30], [6,  2]],
              [[5, 1], [19,  1], [14, 30], [6,  2]]]

This is just an example, and I believe there should be definitely an easy way to do this, but I'm kinda newbie, so I'm not sure exactly the problem, so any help or reference will be appreciated, thank you so much!

Upvotes: 1

Views: 65

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195468

reference = [[[2, 3], [2, 4], [3, 2], [4, 2]],
             [[2, 3], [3, 2], [3, 4], [4, 3]],
             [[2, 3], [3, 2], [3, 4], [4, 3]]]

mydict = {(2, 3): [5, 1], (2, 4): [14, 16], (3, 2): [19, 1], (3, 4): [14, 30], (4, 2): [16, 9], (4, 3): [6, 2]}


out = [[mydict.get(tuple(v), v) for v in row] for row in reference]

from pprint import pprint
pprint(out)

Prints:

[[[5, 1], [14, 16], [19, 1], [16, 9]],
 [[5, 1], [19, 1], [14, 30], [6, 2]],
 [[5, 1], [19, 1], [14, 30], [6, 2]]]

Upvotes: 2

Related Questions