为什么python dict对象会打开元组中的一个单独元素,但如果这是一个list对象,它会将它保存在容器中?

2024-04-25 13:10:38 发布

您现在位置:Python中文网/ 问答频道 /正文

当我想访问dict中的tuple的单个元素时,我得到了一个看起来很奇怪的错误

下面是dict对象:

>>> x = {"palermo":{"country":"ARG",
... "utc":-3,
... "apply_time_change":(False), #other dicts are (True , "Region of the world")
... "hemisphere":"S"
... }}

>>> x['palermo']['apply_time_change'][0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bool' object is not subscriptable

真让人吃惊,但当我检查物体时:

>>> x['palermo']
{'country': 'ARG', 'utc': -3, 'apply_time_change': False, 'hemisphere': 'S'}

tuple消失了。它打开了包装。我想知道在python3中,在dict中打开iterable的alone元素是否是一个新功能,但事实并非如此,因为在list中,它将alone元素保留在其中。为什么?它的目标是什么?因为对我来说它只会产生一个bug

Ubuntu 18.04.3下的Python 3.7.4


Tags: 对象false元素time错误argchangecountry