Reputation: 39
I have a dictionary where each value is a list of variables (all variables are floats):
d = {1:[a,b,c], 2:[d,e,f], 3:[g,h,i]}
and a list with the same number of elements as there are elements in the combined lists of the dictionary:
L = [1,2,3,4,5,6,7,8,9]
I want to combine the list into the dictionary, such that:
d = {1:[a+1,b+2,c+3], 2:[d+4,e+5,f+6], 3:[g+7,h+8,i+9]}
What is a good way to do this?
Upvotes: 0
Views: 70
Reputation: 24232
Here is a way to do it.
As your question was unclear about what a
, b
and so on were supposed to be when you first asked your question, I used strings for simplicity. It would work all the same with floats.
d = {1:['a', 'b', 'c'], 2:['d', 'e', 'f'], 3:['g', 'h', 'i']}
L = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
L_iter = iter(L)
new_d = {key: [val + next(L_iter) for val in sublist] for key, sublist in d.items()}
print(new_d)
# {1: ['a1', 'b2', 'c3'], 2: ['d4', 'e5', 'f6'], 3: ['g7', 'h8', 'i9']}
We create the new dict with a dict comprehension. Inside it, we create the new sublist with a list comprehension, iterating on L
with the help of the iterator L_iter
, which allows to get the next item of L
each time.
Upvotes: 1