Andrew Earl
Andrew Earl

Reputation: 363

Replacing values in one dictionary with the keys in another dictionary

I have two dictionaries:

dict_1 = {0:[300,650], 1:[420,800], 2:[700,400]}
dict_2 =  {0.0: [[300,650], [895, 111]], 1.0: [[700, 400], [420, 800]], 2.0: [[100, 800], [200, 400]]

If a value in dict_1 is equal to one of the values in the lists in dict_2 then the value in dict_2 must be replaced with the KEY corresponding to the value in dict_1.

From the above dictionaries the output I want is:

dict_2 = {0.0: [0, [895, 111]], 1.0: [2, 1], 2.0: [[100, 800], [200, 400]]

This is how far I've gotten:

x = 0
for i in dict_2:
    for node in dict_1:
        if dict_2[x][0] == dict_1[x]:
            dict_2[x][0] = dict_1[???]
        if dict_2[x][1] == dict_1[x]:
            dict_2[x][1] = dict_1[???]
    x+=1

All I'm really struggling with is how to call the key of dict_1 and not a value associated with the key of dict_1 - and obviously my code could be more efficient.

Thanks

Upvotes: 0

Views: 467

Answers (3)

Viper
Viper

Reputation: 505

This should work :

dict_1 = {0:[300,650], 1:[420,800], 2:[700,400]}
dict_2 =  {0.0: [[300,650], [895, 111]], 1.0: [[700, 400], [420, 800]], 2.0: [[100, 800], [200, 400]]}

for key_2 in dict_2:
    for key_1 in dict_1:
        for i in range(0, len(dict_2[key_2])): # In case you change the dimension of dict_2
            if dict_2[key_2][i] == dict_1[key_1]:
                dict_2[key_2][i] = key_1

Upvotes: 0

niemmi
niemmi

Reputation: 17263

Assuming that the values in dict_1 are unique you reverse it by converting lists to tuples. Then you can use dict comprehension with nested list comprehension to create the final result:

dict_1 = {0:[300,650], 1:[420,800], 2:[700,400]}
dict_2 =  {0.0: [[300,650], [895, 111]], 1.0: [[700, 400], [420, 800]], 2.0: [[100, 800], [200, 400]]}

inverse = {tuple(v): k for k, v in dict_1.items()}
res = {k: [inverse.get(tuple(l), l) for l in v] for k, v in dict_2.items()}
print(res)

Output:

{0.0: [0, [895, 111]], 1.0: [2, 1], 2.0: [[100, 800], [200, 400]]}

Upvotes: 3

Carele
Carele

Reputation: 774

You can create a reversed dict_1 to have the keys instead of the values.

dict_1_rev = {v:k for k,v in a.items()}

so :

x = 0
for i in dict_2:
    for node in dict_1:
        if dict_2[x][0] == dict_1[x]:
            dict_2[x][0] = dict_1_rev[dict_1[x]]
        if dict_2[x][1] == dict_1[x]:
            dict_2[x][1] = dict_1_rev[dict_1[x]]
    x+=1

Note that this cannot work if you have duplicate values in dict one. Keys must be unique for your problem.

Up to you to make it more efficient, though. That is another question.

Upvotes: 0

Related Questions