Python中bunch类型和dictionary类型有什么区别?

13

我发现sklearn.utils.Bunchdict基本上是一样的。例如,如果有一个dict对象,比如说

dict_1 = {"a":1, "b":2}

并且一个bunch对象称为bunch

bunch_1 = Bunch(a=1, b=2)

两者具有相同的行为集。


2
由于这不是标准内置类,您应该确切地说明它的来源。 - deceze
从sklearn模块中,datasets.load_iris()返回的对象类型为Bunch。 - TheLastCoder
2
我不建议使用Bunch,因为该项目已经不再维护(最后一次发布于2011年12月)。请参见https://github.com/dsc/bunch/issues。 - Laurent LAPORTE
有没有类似于bunch的东西?我在哪里可以获得对字典值的属性样式访问? - DataCruncher
1
@fireblaze 这种区别是明确存在的,因此您可以将数据存储在 d['keys'] 中,并使用字典的方法作为 d.keys(),否则这将导致命名冲突。即使大多数情况下您可能不会遇到这种情况,但像 Bunch 这样的类需要处理这个根本性问题。 - deceze
2
@Abhilash Prakash Python 隐藏/放弃字典的键作为属性,请参见 https://dev59.com/-mMm5IYBdhLWcg3wO9Hy - Tommy Levi
2个回答

16

Bunch是Dict类的一个子类,它支持所有与dict相同的方法。此外,它允许你将键作为属性使用。

b = Bunch(a=1, b=2)
>>> b['b']
2
>>> b.b
2

在这里阅读更多


因此,命名空间 - Rodrigo Rodrigues

2
Bunch类似于字典,但支持属性类型访问。
数据类型:
- 字典是内置类型,而Bunch来自bunchclass包。 - Bunch在Python 2中运行良好,但在Python 3中不起作用!您可以从sklearn.utils中导入Bunch。
``` from bunchclass import Bunch # Python 2 from sklearn.utils import Bunch # Python 3 ```
  1. Initialization Initialization of bunch does not require {}, but an explicit function with attributes of the elements you required to be in the bunch.

    d1 = {'a':1, 'b':'one', 'c':[1,2,3], 4:'d'}`
    b1 = Bunch(a=1, b='one', c=[1,2,3])    # Also note: here the keys of Bunch are
                                           # attributes of the class. They must be
                                           # mutable and also follow the
                                           # conventions for variables.
    
  2. Accessing the value of the key This is the main difference between the two.

    d1['a']
    b1['a']
    b1.a
    
在一个Bunch中,您可以使用点符号访问属性。在一个dict中,这是不可能的。 相似之处 字典和bunch都可以包含任何数据类型的值。但键必须是可变的。 可以有嵌套的字典和嵌套的bunch。 Bunch的实用程序
  • Bunch()对于序列化为json很有用。
  • Bunch()用于在sklearn中加载数据。这里通常一个bunch包含各种类型的各种属性(列表、numpy数组等)。
更多关于Bunch的信息 与任何其他对象一样,使用dir(Bunch对象)来了解更多信息。 请参阅此链接以了解有关bunch的更多信息:Bunch 如果您的目标是将一堆数据转换为数据框,您可以参考此链接https://github.com/viswanathanc/basic_python/blob/master/sklearn.utils.bunch%20to%20pandas%20Dataframe.ipynb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接