简体   繁体   English

为什么将Python dict转换为元组会返回一组键?

[英]Why does casting a Python dict to a tuple return a tuple of keys?

I came across some Python code that had me very confused. 我遇到了一些令我非常困惑的Python代码。

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

Basically, I found that casting a dictionary as a tuple returns a tuple of the dictionary's keys. 基本上,我发现将字典作为元组转换会返回字典键的元组。

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

Why does a tuple(dict) return a tuple of keys? 为什么元组(dict)会返回一个键元组? I can make sense of it, but wasn't able to find any documentation or explanation around why. 我可以理解它,但无法找到任何关于原因的文档或解释。 Can anyone explain this? 有谁能解释一下?

Dictionary objects are clearly documented here : 这里清楚地记录字典对象:

iter(d) ITER(d)

Return an iterator over the keys of the dictionary. 在字典的键上返回一个迭代器。

Note, this is why I don't like using the term "cast" when you use list or tuple to convert an iterable into a list or tuple. 注意,这就是为什么当你使用listtupleiterable转换为list或tuple时,我不喜欢使用术语“cast”。 And from the tuple docs : 从元组文档

class tuple([iterable]): class tuple([iterable]):

... ...

The constructor builds a tuple whose items are the same and in the same order as iterable ’s items. 构造函数构建一个tuple其项目与iterable的项目相同且顺序相同。 iterable may be either a sequence, a container that supports iteration, or an iterator object. iterable可以是序列,支持迭代的容器,也可以是迭代器对象。 If iterable is already a tuple, it is returned unchanged. 如果iterable已经是一个元组,则返回不变。 For example, tuple('abc') returns ('a', 'b', 'c') and tuple( [1, 2, 3] ) returns (1, 2, 3) . 例如, tuple('abc')返回('a', 'b', 'c')tuple( [1, 2, 3] )返回(1, 2, 3) If no argument is given, the constructor creates a new empty tuple, () . 如果没有给出参数,构造函数将创建一个新的空元组()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM