Dileesh Dil
Dileesh Dil

Reputation: 199

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'

Upvotes: 12

Views: 69446

Answers (4)

JSowa
JSowa

Reputation: 10572

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}

Upvotes: 6

Gautam
Gautam

Reputation: 1932

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

Upvotes: 1

user10076130
user10076130

Reputation: 476

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

Upvotes: 29

DerAktionaut
DerAktionaut

Reputation: 66

You could use

dict["key"] = value_list 

so in your case:

mydict["key"] = z

as described here: Python docs

Upvotes: 4

Related Questions