简体   繁体   中英

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.

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? 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)

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. And from the tuple 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, () .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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