TypeError: 'dict' object is not callable while using dict( )

前端 未结 3 831
余生分开走
余生分开走 2021-01-18 11:31

I was using Python 2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609] on linux2 , when i ran the folllowing code in it the corresponding error is shown .I searche

相关标签:
3条回答
  • 2021-01-18 12:01

    In a fresh interpreter:

    >>> bob=dict(name='bob smith',age=42,pay='10000',job='dev')
    >>> bob
    {'age': 42, 'pay': '10000', 'job': 'dev', 'name': 'bob smith'}
    

    However, you are getting a TypeError:

    TypeError: 'dict' object is not callable

    This error you get tells you that your dict is not callable.

    Since my dict is callable when I open a fresh interpreter, it means that your dict is different.

    Most likely, you defined a dict variable, which overrode the built-in dict. Look for the

    dict = {...}
    

    line, and rename your variable.

    As pointed out by @Robᵩ, don't use built-in names for your variables. Especially avoid the tempting str, list, and so on.

    0 讨论(0)
  • 2021-01-18 12:08

    On a previous line in that interactive session, you have rebound the dict name to some variable. Perhaps you have a line like dict={1:2} or dict=dict(one=1, two=2).

    Here is one such session:

    >>> dict=dict(one=1)
    >>> bob=dict(name='bob smith',age=42,pay='10000',job='dev')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'dict' object is not callable
    >>> 
    

    As a general rule, one should not use built-in type names as variable names, to prevent this error.

    0 讨论(0)
  • 2021-01-18 12:08

    edit: Ignore this, I am told this is bad practice.

    As mgilson stated, the issue is likely that you have a variable called dict. The solution to this would be to run

    del dict
    

    which deletes the variable by that name.

    0 讨论(0)
提交回复
热议问题