Constructing Key:Value pair from list comprehension in Python
I am trying to extend some code.

What works:

pretrained_dict = {k: v for k, v pretrained_dict.items if k in model_dict}


However, if I extend it to:

pretrained_dict = {k: v if k in model_dict else k1:v1 for k, v, k1, v1 in zip(pretrained_dict.items(), model_dict.items()) }


The code fails, If I put the else at the end it still fails:

 pretrained_dict = {k: v if k in model_dict for k, v, k1, v1 in zip(pretrained_dict.items(), model_dict.items()) else k1:v1}
                                                 ^
SyntaxError: invalid syntax


How can I construct the key value pair using an if else condition over two lists?

You can use a ChainMap to achieve what you want without having to use comprehensions at all

from collections import ChainMap
pretrained_dict = ChainMap(pretrained_dict, model_dict)


This returns a dictionary-like object that will lookup keys in pretrained_dict first and if it is not present then lookup the key in model_dict
