Polymorphism
Polymorphism

Reputation: 385

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.setdefault(linko.text.encode('UTF-8'),{}).append(allArticle)
else:
    indexDb[linko.text.encode('UTF-8')] = allArticle

Upvotes: 1

Views: 738

Answers (2)

VBB
VBB

Reputation: 1325

The command is not append, but you can add an entire dict as below:

dict1 = {'a':1, 'b':2}
dict2 = {'c':3, 'd':4}
dict3 = dict1.append(dict2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'append'
dict1['dict2'] = dict2
dict1
{'a': 1, 'b': 2, 'dict2': {'c': 3, 'd': 4}}

Perhaps you meant that you want to add each key from dict2 to dict1. In that case the command will be,

for key in dict2:
    dict1[key] = dict2[key]

dict1
{'a': 1, 'c': 3, 'b': 2, 'd': 4}

Upvotes: 0

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52213

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)

Upvotes: 1

Related Questions