将数据附加到python字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51325708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
appending data to python dictionary
提问by Dileesh Dil
I have used the following code to initialize a dictionary from the list of keys
z=df1[2].value_counts().keys().tolist()
mydict=dict.fromkeys(z,None)
我使用以下代码从键列表中初始化字典
z=df1[2].value_counts().keys().tolist()
mydict=dict.fromkeys(z,None)
further, I have used
此外,我已经使用
`value=df2[2].value_counts().keys().tolist()
counts=df2[2].value_counts().tolist()`
for j,items in value:
if mydict.has_key(items):
mydict.setdefault(items,[]).append(counts[j])
it is generating the following error
它产生以下错误
mydict.setdefault(items,[]).append(counts[j]) AttributeError: 'NoneType' object has no attribute 'append'
mydict.setdefault(items,[]).append(counts[j]) AttributeError: 'NoneType' 对象没有属性 'append'
回答by user10076130
Append works for arrays, but not dictionaries.
追加适用于数组,但不适用于字典。
To add to a dictionary use dict_name['item'] = 3
添加到字典使用 dict_name['item'] = 3
Another good solution (especially if you want to insert multiple items at once) would be: dict_name.update({'item': 3})
另一个好的解决方案(特别是如果您想一次插入多个项目)是: dict_name.update({'item': 3})
The NoneType error comes up when an instance of a class or an object you are working with has a value of None
. This can mean a value was never assigned.
当您正在使用的类或对象的实例的值为 时,会出现 NoneType 错误None
。这可能意味着从未分配过值。
Also, I believe you are missing a bracket here: mydict.setdefault(items,]).append(counts[j])
It should be: mydict.setdefault(items,[]).append(counts[j])
另外,我相信您在这里缺少一个括号: mydict.setdefault(items,]).append(counts[j])
它应该是:mydict.setdefault(items,[]).append(counts[j])
回答by DerAktionaut
You could use
你可以用
dict["key"] = value_list
so in your case:
所以在你的情况下:
mydict["key"] = z
as described here: Python docs
如此处所述: Python 文档
回答by Gautam
The reason for your error is that you are trying to append to the result of mydict.setdefault()
which is actually None as that method returns nothing. Apart from that do also take note of other answers that to a dictionary in python, you do not append
你的错误的原因是你试图附加到结果mydict.setdefault()
实际上是 None 因为该方法不返回任何内容。除此之外,还要注意python中字典的其他答案,你没有append
回答by Tajni
mydict = {}
print(mydict) # {}
Appending one key:
追加一键:
mydict['key1'] = 1
print(mydict) # {'key1': 1}
Appending multiple keys:
附加多个键:
mydict.update({'key2': 2, 'key3': 3})
print(mydict) # {'key1': 1, 'key2': 2, 'key3': 3}