在for循环中,我有以下内容:
aContract = {'name': 'abc', 'type': 'xyz'}
if 'contracts' in alist:
alist["contracts"].append(aContract)
else:
alist["contracts"] = aContract
所以json被归还给我,在json里面我们有bool,dict,list等等'contract'在这个json中作为列表。当我的代码在if语句中时,我可以将其添加到其中。但是,当'contract'不存在时(我们在else语句中),我正在尝试创建它(不成功)并向其添加aContract。所以else语句使它成为一个词典,下次我尝试运行
时alist["contracts"].append(aContract)
我收到错误:
AttributeError: 'dict' object has no attribute 'append'
当我想要一个列表时,我创建了一个字典。那么如何让'合约'作为一个列表存在,然后添加'aContract'呢?
答案 0 :(得分:1)
将字典放在文字列表中:
aContract = {'name': 'abc', 'type': 'xyz'}
if 'contracts' in alist:
alist["contracts"].append(aContract)
else:
alist["contracts"] = [aContract]
更好的是,在这里使用dict.setdefault()
来跳过必须测试密钥:
aContract = {'name': 'abc', 'type': 'xyz'}
alist.setdefault("contracts", []).append(aContract)
dict.setdefault()
会将键设置为默认值(如果尚未存在),则返回该值。因此,如果alist
没有键'contracts'
,则会将值设置为空列表。