Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Appending a dictionary of values to a dictionary of lists with same keys

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{'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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading