gpt4 book ai didi

python - python的dict构造函数是如何处理Mappings的?

转载 作者:行者123 更新时间:2023-11-28 17:29:35 24 4
gpt4 key购买 nike

dict(mapping) 实际上做了什么?

背景:

Python 的文档建议有 three possible paths在构建 dict 时,其中之一是使用 Mapping

pandas series 在某些方面类似于 dict,并且强制转换为 dict 可以按预期工作:

In [27]: series=pd.Series({'a':2,'b':3})

In [28]: dict(series)
Out[28]: {'a': 2, 'b': 3}

但是当在 ChainMap 中时,这会出错:

In [25]: dict(ChainMap(series))

...我认为这应该等同于第一个表达式,但是...

---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pandas/core/index.py in get_value(self, series, key)
1789 try:
-> 1790 return self._engine.get_value(s, k)
1791 except KeyError as e1:

pandas/index.pyx in pandas.index.IndexEngine.get_value (pandas/index.c:3204)()

pandas/index.pyx in pandas.index.IndexEngine.get_value (pandas/index.c:2903)()

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:3843)()

pandas/hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12265)()

pandas/hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12216)()

KeyError: 2

During handling of the above exception, another exception occurred:

IndexError Traceback (most recent call last)
<ipython-input-25-ffe959c53a67> in <module>()
----> 1 dict(ChainMap(series))

/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/collections/__init__.py in __getitem__(self, key)
865 for mapping in self.maps:
866 try:
--> 867 return mapping[key] # can't use 'key in mapping' with defaultdict
868 except KeyError:
869 pass

/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pandas/core/series.py in __getitem__(self, key)
555 def __getitem__(self, key):
556 try:
--> 557 result = self.index.get_value(self, key)
558
559 if not np.isscalar(result):

/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pandas/core/index.py in get_value(self, series, key)
1794
1795 try:
-> 1796 return tslib.get_value_box(s, key)
1797 except IndexError:
1798 raise

pandas/tslib.pyx in pandas.tslib.get_value_box (pandas/tslib.c:16375)()

pandas/tslib.pyx in pandas.tslib.get_value_box (pandas/tslib.c:16126)()

IndexError: index out of bounds

FWIW 这确实有效:

In [29]: dict(ChainMap(dict(series)))
Out[29]: {'a': 2, 'b': 3}

...因此 ChainMap 似乎正在调用 dict 未调用的 Series 接口(interface)部分。我不知道是什么,因为我似乎找不到复制 dict(mapping) 功能的 Python 代码。

最佳答案

看起来系列并不是真正的映射...请注意,迭代系列会产生值,而不是键:

>>> list(series)
[2, 3]

collections.ChainMap 依赖于迭代映射应该产生键这一事实。

显然,dict 构造函数不依赖于这个事实(IIRC,它使用 .keys 方法——pandas 返回一个合适的对象)。

关于python - python的dict构造函数是如何处理Mappings的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35442924/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com