Search code examples
pythondictionarykey

how to copy values ​from one dictionary to keys of a second dictionary


I have two dictionaries dic1 and dic2 in this format:

dic1 = {'a':1, 'b':2}
dic2 = {'c':3, 'd':4}

I would love to obtain a dic3 with same key of dic2 and values of dic1:

dic3 = {'c':1, 'd':2}

How can I combine the keys of dic2 with the values of dic1 to create the result?


Solution

  • Zip keys of second dict with values of the first dict and call dict on the result:

    dic3 = dict(zip(dic2.keys(), dic1.values()))
    # dic3 = dict(zip(dic2, dic1.values()))
    print (dic3)
    {'c': 1, 'd': 2}
    

    dic3 = {k : v for k, v in zip(dic2.keys(), dic1.values())}
    print (dic3)
    {'c': 1, 'd': 2}