[Tutor] Is there a programmatic use for keys() and values()

Steven D'Aprano steve at pearwood.info
Sat Jun 15 21:37:20 CEST 2013


On 16/06/13 04:41, Jim Mooney wrote:
> When I try to get the keys of a dictionary, such as d.keys(), I get
> the below instead of a plain list, and it's not very usable. How can I
> use the keys from this like it was a list, or is this basically
> useless other than to see the keys or values?
>
> *** Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC
> v.1600 32 bit (Intel)] on win32. ***
>>>> d.keys()
> dict_keys(['alpha', 'olf', 'bog', 'dog'])


What you are seeing is called a dict "view" -- it's a live snapshot of the dicts keys, and will update automatically as the dict updates.

You can iterate over it as if it were a list:

for key in d.keys():
     print(key)


You can convert it to a list (in which case it will no longer update automatically):

keys = list(d.keys())


You can apply set operations, such as taking the union or intersection of two views:

py> d1 = dict(a=1, b=2, c=3)
py> d2 = dict(c=5, d=7)
py> d1.keys() | d2.keys()  # All the keys in either dict.
{'d', 'b', 'c', 'a'}
py> d1.keys() & d2.keys()  # The keys in both dicts.
{'c'}



-- 
Steven




More information about the Tutor mailing list