Skip to content
Advertisement

How to modify dictionary values based on an array having key information

dict ={'A':{'x':'123','y':'322','z':'432'},'B':{'x':'24','y':'622','z':'5652'},'C':{'x':'424','y':'682','z':'52'},'D':{'x':'32','y':'96','z':'3'}} 

arr1 = ['A','B','D']

values of key to changed: y,z

I want to change dict value(x,y) based on arr1 such that value of ‘y’ should be equal to ‘z’

Required Dict

dict ={'A':{'x':'123','y':'322','z':'322'},'B':{'x':'24','y':'622','z':'622'},'C':{'x':'424','y':'682','z':'52'},'D':{'x':'32','y':'96','z':'96'}}

Advertisement

Answer

Try:

You can you can iterate over the elements of arr1 then set the value of the z key.

dict1 ={'A':{'x':'123','y':'322','z':'432'},'B':{'x':'24','y':'622','z':'5652'},'C':{'x':'424','y':'682','z':'52'},'D':{'x':'32','y':'96','z':'3'}} 
arr1 = ['A','B','D']

for i in arr1:
    dict1[i]['z']=dict1[i]['y']
print(dict1)

PS: Don’t use keywords like dict as variables because they shadow the inbuilt functions

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement