Home > Mobile >  Appending a dictionary of values to a dictionary of lists with same keys
Appending a dictionary of values to a dictionary of lists with same keys

Time:04-09

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

CodePudding user response:

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.

CodePudding user response:

because you are adding to a list you should user the append() method to add to list

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_v.keys():
    dict_l[key].append(dict_v[key])

print(dict_l)

CodePudding user response:

Here is my answer:

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_v:
  if key in dict_l:
    temp = dict_l[key]
    temp.append(dict_v[key])
    dict_l[key] = temp
  else:
    dict_l[key] = stock_prices[key]
print(dict_l)

So instead of for key in dict_l, I did for key in dict_v just for the sake of logic. I also appended key value from dict_v to dict_l, but in your code you appended the key value from dict_l to dict_v, and I changed that. Hope it helps!

  • Related