[Python-ideas] Enhancing dict.values

Ethan Furman ethan at stoneleaf.us
Fri May 27 00:57:09 EDT 2016


On 05/26/2016 09:26 PM, Guido van Rossum wrote:
> On Thursday, May 26, 2016, Steven D'Apranowrote:
>> On Thu, May 26, 2016 at 11:28:25PM +0100, Nathan Schneider wrote:

>> I think this is important enough to get a change in subject line, lest
>> it be lost in the dict unpacking thread.
>
>
>
>>> Instead of special syntax, what if dict.values() returned a tuple
>> when given keys as arguments:
>>>
>>>    partner_id, product_id, ship_to, product_ids = my_dict.values(
>>>            'partner_id', 'product_id', 'ship_to', 'product_ids')
>>>
>>> That avoids repeating the dict variable, at least. And as there is
>>> dict.update(), I don't see the need for a new syntax for assigning to
>>> multiple keys.
>>
>> I like this idea. I think it beats the status quo:
>>
>> +1
>
> Interesting. It should probably have a different name. What type should
> it return? Iterator? Sequence? It can't really be a ValuesView because
> that class is just a view on the hash table. Even though you technically
> *could* combine this functionality into values(), I don't think it would
> be helpful to do so -- if only because of the surprising edge case where
> if you were to pass it a list of keys to extract using **args, if the
> list is empty, values() would default to its original behavior or
> returning all keys, in hash table order.

Good point.  The time bomb would be even worse if sometimes the dict had 
the same number of elements as were being asked for, as then it would be 
an intermittent problem.

However, if we make a new method we could just as easily make a new 
function:

   def get_values_from(a_dict, keys=()):
       if not keys:
            raise an_error
       yield a_dict[k] for k in keys

Hmmm.  That could even be handy for a list/tuple:

   offset, name = get_values_from(a_list, [1, 7])

;)

At any rate, the return type should be an iterator.

--
~Ethan~



More information about the Python-ideas mailing list