Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

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'

like image 389
Dileesh Dil Avatar asked Jul 13 '18 12:07

Dileesh Dil


2 Answers

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])

like image 168
user10076130 Avatar answered Sep 26 '22 01:09

user10076130


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}
like image 27
Jsowa Avatar answered Sep 22 '22 01:09

Jsowa