Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get dictionary keys and values if both keys are in two separated dictionaries?

I would like to get a new dictionary with keys only if both dictionaries have those keys in them, and then get the values of the second one.

# example:

Dict1 = {'A':3, 'B':5, 'C':2, 'D':5}
Dict2 = {'B':3, 'C':1, 'K':5}

# result--> {'B':3, 'C':1} 
like image 253
DarkWarrior Avatar asked Nov 06 '25 06:11

DarkWarrior


2 Answers

As a dictionary comprehension:

>>> {k:v for k, v in Dict2.items() if k in Dict1}
{'B': 3, 'C': 1}
like image 148
CDJB Avatar answered Nov 08 '25 21:11

CDJB


Or use filter:

>>> dict(filter(lambda x: x[0] in Dict1, Dict2.items()))
{'B': 3, 'C': 1}
>>>
like image 25
U12-Forward Avatar answered Nov 08 '25 22:11

U12-Forward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!