appending data to python dictionary

两盒软妹~` 提交于 2021-02-18 22:49:36

问题


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)

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'


回答1:


Append works for arrays, but not dictionaries.

To add to a dictionary use dict_name['item'] = 3

Another good solution (especially if you want to insert multiple items at once) would be: 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.

Also, I believe you are missing a bracket here: mydict.setdefault(items,]).append(counts[j]) It should be: mydict.setdefault(items,[]).append(counts[j])




回答2:


You could use

dict["key"] = value_list 

so in your case:

mydict["key"] = z

as described here: Python docs




回答3:


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}



回答4:


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



来源:https://stackoverflow.com/questions/51325708/appending-data-to-python-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!