newbzzs
newbzzs

Reputation: 305

Updating Nested dictionary with new information in table/dictionary using update

Given the following dictionary:

dict1 = {'AA':['THISISSCARY'],
         'BB':['AREYOUAFRAID'],
         'CC':['DONOTWORRY']}

I'd like to update the values in the dictionary given the information in the following table

Table = pd.DataFrame({'KEY':['AA','AA','BB','CC'],
                      'POSITION':[2,4,9,3],
                      'oldval':['I','I','A','O'],
                      'newval':['X','X','U','I']})

that looks like this

   KEY   POSITION  oldval  newval
0   AA         2      I      X
1   AA         4      I      X
2   BB         9      A      U
3   CC         3      O      I

The end result should look like this:

dict1 = {'AA':['THXSXSSCARY'],
         'BB':['AREYOUAFRUID'],
         'CC':['DONITWORRY']}

Essentially, I'm using the KEY and POSITION to find the location of the value in the dictionary then if the oldvalue matches the one in the dictionary, then replacing it with the newval

I've been looking at the update function where I'd convert my table to a dictionary but I'm unsure how to apply to my example.

Upvotes: 1

Views: 65

Answers (2)

mozway
mozway

Reputation: 260725

First craft a nested Series/dictionary to map the key/position/newval, then use a dictionary comprehension:

s = (Table.groupby('KEY')
     .apply(lambda d: d.set_index('POSITION')['newval'].to_dict())
     )

out = {k: [''.join(s.get(k, {}).get(i, x) for i,x in enumerate(v[0]))]
       for k,v in dict1.items()
       }

Output:

{'AA': ['THXSXSSCARY'],
 'BB': ['AREYOUAFRUID'],
 'CC': ['DONITWORRY']}

Intermediate s:

KEY
AA    {2: 'X', 4: 'X'}
BB            {9: 'U'}
CC            {3: 'I'}
dtype: object

Upvotes: 1

Bushmaster
Bushmaster

Reputation: 4608

you can use:

dict_df=Table.to_dict('records')
print(dict_df)
'''
[{'KEY': 'AA', 'POSITION': 2, 'oldval': 'I', 'newval': 'X'}, {'KEY': 'AA', 'POSITION': 4, 'oldval': 'I', 'newval': 'X'}, {'KEY': 'BB', 'POSITION': 9, 'oldval': 'A', 'newval': 'U'}, {'KEY': 'CC', 'POSITION': 3, 'oldval': 'O', 'newval': 'I'}]
'''

for i in list(dict1.keys()):
    for j in dict_df:
        if i == j['KEY']:
            mask=list(dict1[i][0])
            mask[j['POSITION']]=j['newval']
            dict1[i]=["".join(mask)]
print(dict1)
# {'AA': ['THXSXSSCARY'], 'BB': ['AREYOUAFRUID'], 'CC': ['DONITWORRY']}

Upvotes: 1

Related Questions