简体   繁体   English

在Python中将项目添加到aa字典中

[英]Adding a item into a a dictionary in Python

I have a dictionary that store the values as lists for each key. 我有一本字典,将值存储为每个键的列表。 For example: 例如:

dict1={}
dict1["A"]=[]

I want to append numbers into this list now, but how do I do this correctly? 我现在想将数字添加到此列表中,但是如何正确执行此操作? I tried dict1["A"]=dict1["A"].append(1) 我尝试了dict1["A"]=dict1["A"].append(1)

this only appended "None" . 这仅附加了"None" How do I do this? 我该怎么做呢?

You just need to call append() 您只需要调用append()

dict1["A"].append(1)

Since the return value of append() itself is None, your version just replaced the old value (a list) with None after you successfully added the item to the list. 由于append()本身的返回值为None,因此您将版本成功添加到列表 ,您的版本仅将旧值(列表)替换为None

A quick demo: 快速演示:

>>> dict1 = {'A': []}
>>> dict1['A'].append(1)
>>> dict1
{'A': [1]}

In Python, in-place operations such as appending to the list, return None : 在Python中,就地操作(例如追加到列表)返回None

>>> alist = []
>>> alist.append(1) is None
True
>>> alist
[1]

but as you can see, the list itself was changed. 但是如您所见,列表本身已更改。

No need to reassign. 无需重新分配。 Just do dict1["A"].append(1) . 只需执行dict1["A"].append(1)

The mistake you have done is dict1["A"].append(1) returns None and that you were assigning it back to dict1 . 您所做的错误是dict1["A"].append(1)返回None ,并且您dict1其分配回dict1 Which explains the None you were getting... 这就解释了您得到的None ...

That's because append() changes the list in-place and returns None . 这是因为append()就地更改了列表并返回None In your code you assigned that returned Value to dict1["A"] 在您的代码中,您分配了返回Value到dict1["A"]

In [25]: dict1={}

In [26]: dict1["A"]=[]

In [27]: dict1["A"].append(1)  #try print dict1["A"].append(1) here

In [28]: dict1
Out[28]: {'A': [1]}

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

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