Elena Elena - 4 months ago 36
Python Question

Combine 2 dictionaries by key-value in python

I have not found a solution to my question, yet I hope it's trivial.
I have two dictionaries:

contains the order number of a word in a text as key: word as value


contains counts of those words in the text


I want to replace the values in dictA by values in dictB via keys in dictB, checking for nones, replacing by 0.

So output should look like:


Is there a way for doing it, preferentially without introducing own functions?


Use a dictionary comprehension and apply the get method of dict B to return 0 for items that are not found in B:

>>> A = {0:'Roses',1:'are',2:'red', 12:'blue'}
>>> B = {'Roses':2,'are':4,'blue':1}
>>> {k: B.get(v, 0) for k, v in A.items()}
{0: 2, 1: 4, 2: 0, 12: 1}