Appending values to the dictionaries in python

Viewed 94

Have got 2 dictionaries with same number of keys. The name of keys are similar and relatable but not same. The values of each key of both dictionaries are numpy arrays of 200*100 size. Requirement is to append values of one of the dictionaries to the other dictionary and finally retain only one dictionary.

Eg:

Dic1 = {K1: np.array([V1]), K2:np.array([V2]),...,K100:np.array([V100])}

Dic2 = {Ky1: np.array([Va1]), Ky2:np.array([Va2]),...,Ky100:np.array([Va100])}


d2v=[*Dic2.values()]

for k, v in Dic1:
    d2v[k].append(v) 

Both dictionaries contain 100 keys with similar names and the values V1,V2,...V100 and Va1,Va2,....,Va100 are numpy arrays of 200*100 size.

The above logic of unpacking the dictionary Dic2 and appending its values with Dic1 does not seem to work. Any hints to proceed further to append values of one of the dictionaries to the other dictionary and finally retain only one dictionary?

1 Answers

The problem is in the forloop exactly over here :

for k, v in Dic1:
d2v[k].append(v) 

when you iterate over a Dictionary you actually receive key values from the dictionary.Hence you probably got the error "Not enough values to unpack". To fix this issue and get both key and values use Dic1.items() which returns a tuple of each key,value pairs. Here :

for k, v in Dic1.items():
d2v[k].append(v)

This should fix the issue that you are facing.

Related