简体   繁体   English

我正在创建一个字典,但我真的想要一个列表,这种情况下的语法是什么?

[英]Im creating a dict but I really want a list, what is the syntax in this case?

In a for loop I have the following: 在for循环中,我有以下内容:

aContract = {'name': 'abc', 'type': 'xyz'}
if 'contracts' in alist:
    alist["contracts"].append(aContract)
else:
    alist["contracts"] = aContract

So json is being returned to me and inside the json we have bool's, dict's, list's etc. 'contracts' is in this json as a list. 因此,json返回给我,并且在json中有bool,dict,list等。“ contracts”以列表的形式存在于此json中。 I can append things to it just fine when my code is in the if statement. 当我的代码位于if语句中时,我可以在上面附加一些内容。 However, when 'contracts' does not exist (we are in the else statement), I'm trying to create it (unsuccessfully) and add aContract to it. 但是,当“合同”不存在时(我们在else语句中),我正在尝试创建(未成功)并向其中添加aContract。 So the else statement makes it a dict and the next time through when I try to run 所以else语句使它成为字典,下次尝试运行时

alist["contracts"].append(aContract)

I get the error: 我得到错误:

AttributeError: 'dict' object has no attribute 'append'

I created a dict when I wanted a list. 我想要列表时创建了字典。 So how do I make 'contracts' exist as a list and then add 'aContract' to it? 那么,如何使“合同”作为列表存在,然后向其中添加“合同”?

Put the dictionary in a literal list: 将字典放入文字列表中:

aContract = {'name': 'abc', 'type': 'xyz'}
if 'contracts' in alist:
    alist["contracts"].append(aContract)
else:
    alist["contracts"] = [aContract]

Better still, use dict.setdefault() here to skip having to test for the key: 更好的是,在此处使用dict.setdefault()来跳过不必测试密钥的操作:

aContract = {'name': 'abc', 'type': 'xyz'}
alist.setdefault("contracts", []).append(aContract)

dict.setdefault() will set the key to the default value given if not yet present, then returns the value. dict.setdefault()会将密钥设置为给定的默认值(如果尚不存在),然后返回该值。 So, if alist has no key 'contracts' , it'll set the value to an empty list. 因此,如果alist没有关键的'contracts' ,它将把值设置为一个空列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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