Daniel Marostica
Daniel Marostica

Reputation: 43

dict comprehension with condition and keyword check

I am trying to accomplish something like this:

models = {k1: v, k2:v}
grid = {k1: w, k2:w, k3:w}

grid_of_params = {grid.items() if grid.keys() in models for k,v in grid.items()}

print(grid_of_params)
Output: {k1: w, k2:w}

In other words, a dict comprehension which returns items of a dict grid if their keys are present in the dict models.

How to correct this syntax?

Upvotes: 0

Views: 57

Answers (1)

timgeb
timgeb

Reputation: 78690

If I understand correctly, {k:v for k, v in grid.items() if k in models} should do the trick.

Upvotes: 3

Related Questions