AnishM
AnishM

Reputation: 267

How to create a new dictionary from old one using a given mapping?

What I am seeking is a Python function that seeks an old dictionary and a mapping. A new dictionary should be returned using the given mapping from the old dictionary.

old_dic = {"a":"1", "b":"2", "c":"3", "d":"4"}
mapping_dic = {"a":"e", "c":"f", "d":"g"}

Hence, a new dictionary should be formed containing the keys e,f, and g. It should look like:

new_dic = {"e":"1", "f":"3", "g":"4"}

Upvotes: 0

Views: 319

Answers (3)

CDahn
CDahn

Reputation: 1876

Try this:

def numberofbagels(oldmap, trans):
    newmap = {}
    for key in oldmap:
        if key in trans:
            newmap[trans[key]] = oldmap[key]
    return newmap

old_dic = {"a":"1", "b":"2", "c":"3", "d":"4"}
mapping_dic = {"a":"e", "c":"f", "d":"g"}

print "%s"%(str(numberofbagels(old_dic,mapping_dic)))

Upvotes: 0

Fabricator
Fabricator

Reputation: 12782

dict comprehension:

{v: old_dic[k] for k,v in mapping_dic.items()}

outputs:

{'e': '1', 'f': '3', 'g': '4'}

Upvotes: 2

confuser
confuser

Reputation: 76

This could work, but maybe there's a better way:

new_dic = dict((mapping_dic[key], val) for key, val in old_dic.items() if key in mapping_dic)

Upvotes: 0

Related Questions