Elena Elena - 4 days ago 6
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:

dictA:
contains the order number of a word in a text as key: word as value
e.g.

{0:'Roses',1:'are',2:'red'...12:'blue'}


dictB:
contains counts of those words in the text
e.g.

{'Roses':2,'are':4,'blue':1}


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:

{0:2,1:4,2:0...12:1}


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

Answer

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}
Comments