I am given a dictionary of values and a dictionary of lists
dict_v = {'A': 2, 'B': 3, 'C': 4}
&
dict_l = {'A': [1,3,4], 'B': [8,5,2], 'C': [4,6,2]}
I am trying to append the values of dict_v to the values of dict_l.
So I want it to look like this:
{'A': [1,3,4,2], 'B': [8,5,2,3], 'C': [4,6,2,4]}
Ive tried the following code:
for key in dict_l:
if key in dict_v:
dict_v[key]=dict_l[key]+dict_v[key]
else:
dict_l[key]=stock_prices[key]
print(dict_v)
it’s giving me an error message
>Solution :
You can append to a list in this sense like this
dict_v = {'A': 2, 'B': 3, 'C': 4}
dict_l = {'A': [1,3,4], 'B': [8,5,2], 'C': [4,6,2]}
for key in dict_l:
if key in dict_v:
dict_l[key] += [dict_v[key]]
print(dict_l)
The change is that you are appending the value dict_v[key] as a list [dict_v[key]] and appending it to the entries that are already in dict_l[key] using +=. This way you can also append multiple values as a list to an already existing list.