Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add items to an empty set in python

Tags:

python

set

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.

like image 482
user2192774 Avatar asked Jul 07 '13 10:07

user2192774


People also ask

Can you add items to a set in Python?

Once a set is created, you cannot change its items, but you can add new items. To add one item to a set use the add() method.

How do you add multiple values to a set in Python?

To add multiple elements at once we use the Set update() method. It takes an iterable(list, tuple, dictionary) as an argument. We can add single or multiply iterable in the set using the Update() method.

Can you have an empty set in Python?

To create an empty set in python we have to use the set() function without any arguments, if we will use empty curly braces ” {} ” then we will get an empty dictionary. After writing the above code (create an empty set in python), Ones you will print “type(x)” then the output will appear as a “ <class 'set'> ”.

Can we add element in set?

Set is an unordered collection, so added elements can be in any order. The add() method can add a tuple object as an element in the set, as shown below. Note that you can add the same tuple only once as in the case of other elements. Lists and Dictionaries cannot be added to the set because they are unhashable.


2 Answers

D = {} is a dictionary not set.

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

Use D = set():

>>> d = set() >>> type(d) <type 'set'> >>> d.update({1}) >>> d.add(2) >>> d.update([3,3,3]) >>> d set([1, 2, 3]) 
like image 74
Ashwini Chaudhary Avatar answered Sep 19 '22 13:09

Ashwini Chaudhary


>>> 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]) 
like image 26
Sukrit Kalra Avatar answered Sep 18 '22 13:09

Sukrit Kalra