python - 为什么将 Python 字典转换为元组会返回键元组?

标签 python python-2.7 types casting

我遇到了一些让我非常困惑的 Python 代码。

my_dict = {'a': 'b'}
a, = my_dict            # a = 'a'
a, b = my_dict          # ValueError: Too many values to unpack

基本上,我发现将字典转换为元组会返回字典键的元组。

my_dict = {'a': 'b', 'c': 'd'}
a = tuple(my_dict)      # a = ('a', 'c')

为什么 tuple(dict) 返回键的元组?我可以理解它,但无法找到任何有关原因的文档或解释。谁能解释一下吗?

最佳答案

字典对象有明确记录here :

iter(d)

Return an iterator over the keys of the dictionary.

请注意,这就是为什么当您使用 listtuple 转换可迭代对象时,我不喜欢使用术语“cast”到列表或元组中。并来自元组 docs :

class tuple([iterable]):

...

The constructor builds a tuple whose items are the same and in the same order as iterable’s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a tuple, it is returned unchanged. For example, tuple('abc') returns ('a', 'b', 'c') and tuple( [1, 2, 3] ) returns (1, 2, 3). If no argument is given, the constructor creates a new empty tuple, ().

关于python - 为什么将 Python 字典转换为元组会返回键元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49040084/

相关文章:

python - 从字符串对象初始化的列表和元组

Python:float 的子类可以在其构造函数中使用额外的参数吗?

python-2.7 - 处理 Pandas 和 Numpy 中的缺失数据

python - Django 和 Aptana Studio

types - Kotlin 可以在类文件中发出 JSR-305 注释吗

java - 动态查找表示原始 Java 类型的类

Python 和 MySQL 连接

python - 使用 pandas 从 url 读取导入的 csv 文件时出错

python - RGB 是从 ImageGrab.grab().load() 中获取的,是数组还是字符串

python - 试图找到最小的数字