Polymorphism Polymorphism - 1 year ago 165
Python Question

Python Append Dictionary in Dictionary Value

I am using shelve module and I have some categories let's say 'A',B,'C' and I have some article which belong those categories I am making a dictionary key is article name value is any number and in shelve module when I append it says:

AttributeError: 'dict' object has no attribute 'append'

here is my code

indexDb = shelve.open('index.db')
if indexDb.has_key(linko.text.encode('UTF-8')):
indexDb[linko.text.encode('UTF-8')] = allArticle

Answer Source

You should change {} with [], and .append() with .extend() when calling setdefault method.

indexDb.setdefault(linko.text.encode('UTF-8'), []).extend(allArticle)

Btw, you don't have to check if key exists because .setdefault() returns the key value available in the dictionary and if given key is not available then it will return provided default value which is the empty list.

Thus, you might want to update your code as follows:

indexDb = shelve.open('index.db')
indexDb.setdefault(linko.text.encode('UTF-8'), []).extend(allArticle)