简体   繁体   中英

Update in dictionary is overwriting the key value pair in python

I want to create a dictionary such that it consists another key,value pair. while using update method in dictionary it is overwriting the old key,value pair.

import yaml

d1={}
l1=[]
d2={}

with open("testspec.yaml","r") as stream:
    d1.update(yaml.load(stream))

l1=d1['TestSpec'].keys()
print(l1)
for i in l1:
    #d2[i]='None'
    for key,value in d1['TestSpec'][i].items():
        if "STEP" in key:
            d2.update({i : {key :value}})      
            #print(d1['TestSpec'][i])
        else:
            del d1['TestSpec'][i][key]
#print(d1)
print(d2)

output of l1/print(l1):

['A1', 'A2', 'A3', 'A4']

final output/print(d2) :

{'A1': {'STEP_8': 'A1_08'}, 'A2': {'STEP_12': 'A2_12'}, 'A3': {'STEP_34': 'A3_34'}, 'A4': {'STEP_8': 'A4_08'}}

the for loop which is returning the key,value pair from d1['TestSpec'][i].items() are such as STEP_1 : A1_1 STEP_2 : A1_2 so on...

Expected output:

{'A1': {'STEP_1': 'A1_1','STEP_2': 'A1_2','STEP_3': 'A1_3'},} like this for all A2,A3,A4 also.

As far as I know, method update() LITERALLY updates the value of the key. If you want to append another value to existing value that corresponds the key, I would recommend updating the value with old value + new value

Let me know if this answer works for you, or I am wrong about some point.

If I've understood you correctly, you want to add to the existing dictionary returned from the relevant keys.

Replace your .update() line with this:

d2[i][key] = value

Simply put, you wanted to append to the dictionary returned, not overwrite it with another key/value pair.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM