not_so_sure
not_so_sure

Reputation: 15

Why does an error occur when creating a set from a dictionary

I have tried to execute the following basic statements in a python console and what I got is an error saying:

dict object is  not  callable 

The code I executed:

>>> test_dict = {1:"one",2:"two"}
>>> set3= set(test_dict)
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'dict' object is not callable

I have gone through some questions on web but couldn't find and understand anything till now.

Upvotes: 1

Views: 1219

Answers (3)

MikeZhang
MikeZhang

Reputation: 337

The code you posted has no problem run under python3 and python2 . If you got this error,it typically means you have reassign set to another object. You should check the code again.

Python 2.7.9 (default, Apr 13 2015, 11:43:15) 
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.49)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> test_dict = {1:"one",2:"two"}
>>> set3=set(test_dict)
>>> print set3
set([1, 2])
>>> set3.add(3)
>>> print set3
set([1, 2, 3])
>>> set3.pop()
1

and in python3 :

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> test_dict = {1:"one",2:"two"}
>>> set3=set(test_dict)
>>> print(set3)
{1, 2}
>>> set3.add(3)
>>> print(set3)
{1, 2, 3}
>>> set3.pop()
1
>>> print(set3)
{2, 3}

Upvotes: 1

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160627

You are masking the built-in set by assignment.

>>> set = {}

This makes the set name point to a new dictionary object, you can no longer use it as the built in type that creates new set objects:

>>> test_dict = {1:"one", 2:"two"}
>>> set3 = set(test_dict)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable

Don't mask the built-in names, simply delete the name binding you created and now everything will run fine:

>>> del set  # 'undos' the set={} binding 
>>> set3 = set(test_dict)
>>> set3
{1, 2}

Upvotes: 1

phihag
phihag

Reputation: 288220

You can construct a set from a dictionary; the set will be initialized to the set of keys in the dictionary.

However, in your case, the name set has been bound to a dict value, so when you write set, you don't get the built-in set class, but that dictionary. Write set = __builtins__.set to restore it in an interactive shell. In a program, search for set = (or as set) in the code before.

Upvotes: 2

Related Questions