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

Andreas Perstinger andipersti at gmail.com
Sat Jun 15 21:34:07 CEST 2013


Jim Mooney <cybervigilante at gmail.com> 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?

If you really need a list you can use the built-in list() constructor
since the return value of d.keys() is an iterable:

>>> d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> list(d.keys())
['a', 'c', 'b', 'd']

Notice that the order of the keys is arbitrary.

But usually you just iterate over the keys.

(In Python 2, d.keys() actually returns a list).

Bye, Andreas


More information about the Tutor mailing list