我遇到了一些让我非常困惑的 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.
请注意,这就是为什么当您使用 list
或 tuple
转换可迭代对象时,我不喜欢使用术语“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')
andtuple( [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/