Dictionary .keys() and .values() should return a set[withPython3000 in mind]

Delaney, Timothy (Tim) tdelaney at avaya.com
Mon Jul 3 17:19:46 EDT 2006


Paul Rubin wrote:

> "Delaney, Timothy (Tim)" <tdelaney at avaya.com> writes:
>> If you want an independent data set, you have to take a snapshot.
>> For the above, that's doing: 
>> 
>>     k0 = list(d.keys())
> 
> I don't understand.  Why have .keys() at all, if it doesn't get you
> an independent data set?  If all you want is to iterate through the
> dict, you can already do that:
> 
>   for k in d: ....

Several reasons.

d.keys()
d.values()
d.items()

You can only have iter(d) equivalent to iter(*one* of the above).

Also, d.keys() can provide an indexable view i.e. you can index it like
the list currently returned from d.keys(). For most use cases, you can
treat it exactly like you can treat the list returned now - just don't
try adding to it or (probably) removing from it.

Tim Delaney



More information about the Python-list mailing list