【问题标题】:Why does an error occur when creating a set from a dictionary从字典创建集合时为什么会出现错误
【发布时间】:2015-12-10 14:14:44
【问题描述】:

我尝试在 python 控制台中执行以下基本语句,但得到的是一条错误消息:

dict object is  not  callable 

我执行的代码:

>>> 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

我在网上浏览了一些问题,但直到现在都找不到和理解任何东西。

【问题讨论】:

  • 一个字典有键值对pairs ...你希望什么项目出现在你的集合中?
  • 你并没有告诉我们一切。您的代码本身不会引发异常。
  • @PaulBecotte 默认情况下,每次迭代字典时都会使用键。
  • set(test_dict) 提供密钥,即:set([1, 2])。但是,如果您在上面的代码中声明了类似set = {...} 的内容,那么您只能为此感到内疚。顺便说一句,从不为您自己的变量使用 Python 标准名称,例如 list、set 或 dict。

标签: python dictionary set callable


【解决方案1】:

您可以从字典中构造一个集合;该集合将被初始化为字典中的键集合。

但是,在您的情况下,名称 set 已绑定到一个 dict 值,因此当您编写 set 时,您不会获得内置的 set 类,而是那个字典。写 set = __builtins__.set 在交互式 shell 中恢复它。在程序中,在前面的代码中搜索set =(或as set)。

【讨论】:

  • @avinash625 请说明如何,以便其他人可以从您的解决方案中受益!如果这个或任何其他答案解决了它,请考虑accepting it。如果问题是其他问题,请写下您自己的答案(稍后接受)。谢谢!
  • 搜索了 set = {} 并删除了我创建的绑定,然后它运行良好
【解决方案2】:

您正在通过赋值屏蔽内置的set。

>>> set = {}

这使得set 名称指向一个新的字典对象,您不能再将它用作创建新set 对象的内置类型:

>>> 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

不要掩盖built-in names,只需删除您创建的名称绑定,现在一切都会正常运行:

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

【讨论】:

    【解决方案3】:

    您发布的代码在 python3 和 python2 下运行没有问题。如果您收到此错误,通常意味着您已将设置重新分配给另一个对象。您应该再次检查代码。

    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
    

    在 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}
    

    【讨论】:

      猜你喜欢
      • 2016-08-13
      • 1970-01-01
      • 2014-12-16
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 2020-11-21
      • 2012-11-19
      • 2020-05-22
      相关资源
      最近更新 更多