[python] How can I add items to an empty set in python

I have the following procedure:

def myProc(invIndex, keyWord):
    D={}
    for i in range(len(keyWord)):
        if keyWord[i] in invIndex.keys():
                    D.update(invIndex[query[i]])
    return D

But I am getting the following error:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
TypeError: cannot convert dictionary update sequence element #0 to a sequence

I do not get any error if D contains elements. But I need D to be empty at the beginning.

This question is related to python set

The answer is


When you assign a variable to empty curly braces {} eg: new_set = {}, it becomes a dictionary. To create an empty set, assign the variable to a 'set()' ie: new_set = set()


>>> d = {}
>>> D = set()
>>> type(d)
<type 'dict'>
>>> type(D)
<type 'set'>

What you've made is a dictionary and not a Set.

The update method in dictionary is used to update the new dictionary from a previous one, like so,

>>> abc = {1: 2}
>>> d.update(abc)
>>> d
{1: 2}

Whereas in sets, it is used to add elements to the set.

>>> D.update([1, 2])
>>> D
set([1, 2])