[英]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): l1 / print(l1)的输出:
['A1', 'A2', 'A3', 'A4']
['A1','A2','A3','A4']
final output/print(d2) : 最终输出/打印(d2):
{'A1': {'STEP_8': 'A1_08'}, 'A2': {'STEP_12': 'A2_12'}, 'A3': {'STEP_34': 'A3_34'}, 'A4': {'STEP_8': 'A4_08'}}
{'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... 从d1 ['TestSpec'] [i] .items()返回键,值对的for循环,例如
STEP_1 : A1_1 STEP_2 : A1_2
依此类推...
Expected output: 预期产量:
{'A1': {'STEP_1': 'A1_1','STEP_2': 'A1_2','STEP_3': 'A1_3'},} like this for all A2,A3,A4 also.
{'A1':{'STEP_1':'A1_1','STEP_2':'A1_2','STEP_3':'A1_3'},}同样适用于所有A2,A3,A4。
As far as I know, method update()
LITERALLY updates the value of the key. 据我所知,方法
update()
会更新键的值。 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
如果要在与键对应的现有值上附加另一个值,建议使用
old value + new value
更新该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: 将您的
.update()
行替换为:
d2[i][key] = value
Simply put, you wanted to append to the dictionary returned, not overwrite it with another key/value pair. 简而言之,您想添加到返回的字典中,而不是用另一个键/值对覆盖它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.