将数据附加到python字典 [英] appending data to python dictionary
问题描述
我已使用以下代码从键列表中初始化字典
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)
我已经用过
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])
它正在产生以下错误
mydict.setdefault(items,[]).append(counts [j])AttributeError:'NoneType'对象没有属性'append'
mydict.setdefault(items,[]).append(counts[j]) AttributeError: 'NoneType' object has no attribute 'append'
推荐答案
Append适用于数组,但不适用于字典.
Append works for arrays, but not dictionaries.
要添加到字典中,请使用 dict_name ['item'] = 3
To add to a dictionary use dict_name['item'] = 3
另一个好的解决方案(尤其是如果您想一次插入多个项目)将是: dict_name.update({'item':3})
Another good solution (especially if you want to insert multiple items at once) would be: dict_name.update({'item': 3})
当您正在使用的类或对象的实例的值为 None
时,出现NoneType错误.这可能意味着从未分配过一个值.
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.
此外,我相信您在这里缺少括号: mydict.setdefault(items,]).append(counts [j])
应该是: mydict.setdefault(items,[]).append(counts [j])
Also, I believe you are missing a bracket here: mydict.setdefault(items,]).append(counts[j])
It should be: mydict.setdefault(items,[]).append(counts[j])
这篇关于将数据附加到python字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!