Umer
Umer

Reputation: 35

Remap dictionary with new dictionary

I want to replace dictionary keys as well as values with the new dictionary in Python.

For instance:

dic1 = {'A': 1, 'B': 2, 'C': 3, 'D': 4}
dic2 = {'A': ['B', 'C', 'D','K'], 'C': ['C', 'D', 'A', 'F'], 'D': ['A', 'B', 'C'] }

In Dic2 I have 'K' and 'F' values that are not present in dic1. I want to remove them as well. I want output in the following form:

out_dic = {1: [2, 3, 4], 3: [3, 4, 1], 4: [1, 2, 3]}

I have found a solution that is not fast enough. First I replace the values of the dictionary with new values. Then update the keys with new keys.

Upvotes: 1

Views: 259

Answers (2)

Tomerikoo
Tomerikoo

Reputation: 19422

dic1 serves as a mapping of values according to which you want to replace all values in dic2. So just iterate on all items of dic2 and use the mapping to replace them:

dic3 = {}
for key, values in dic2.items():
    dic3[dic1[key]] = [dic1[value] for value in values]

print(dic3)

If you have values in dic2 that might not be present in dic1, change to this to leave them as they were in dic2:

    dic3[dic1.get(key, key)] = [dic1.get(value, value) for value in values]

And if you want to completely remove them, use:

for key, values in dic2.items():
    if key in dic1:
        dic3[dic1[key]] = [dic1[value] for value in values if value in dic1]

Which gives:

{1: [2, 3, 4], 3: [3, 4, 1], 4: [1, 2, 3]}

Upvotes: 2

hussic
hussic

Reputation: 1920

new = {
    v: [dic1[v2] for v2 in dic2[k] if v2 in dic1]
        for k, v in dic1.items() if k in dic2
}

Upvotes: 0

Related Questions