Reputation: 43
Say that I have two Python dictionaries:
dictA = {20: [0.5, 1, 0.5], 25: [0.5, 1, 0.5]}
dictB = {20: 0.4, 25: 0.5}
The first dictionary contains keys with a list of floats as its value. The second one contains similar keys with a float value. I want the result to be the sum of the float value of dictB to each value in the list of dictA:
dictResult = {20: [0.9, 1.4, 0.9], 25: [1, 1.5, 1]}
I'm trying to do this one the simplest way possible without resorting to many lines of code; (wanted to make my code a bit more maintainable and readable in the future). Can this be accomplished using comprehensions?
Upvotes: 1
Views: 216
Reputation: 10960
Use dictionary comprehension
{ k: [x + dictB.get(k,0) for x in l] for k, l in dictA.items() }
Output
{20: [0.9, 1.4, 0.9], 25: [1.0, 1.5, 1.0]}
Upvotes: 6