Python 3: dict & dict.keys()

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Jul 25 03:27:40 EDT 2013


On Thu, 25 Jul 2013 16:02:42 +1000, Chris Angelico wrote:

> On Thu, Jul 25, 2013 at 3:48 PM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> Dicts aren't sets, and don't support set methods:
>>
>> py> d1 - d2
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in <module>
>> TypeError: unsupported operand type(s) for -: 'dict' and 'dict'
> 
> I wouldn't take this as particularly significant, though. A future
> version of Python could add that support (and it might well be very
> useful), without breaking any of the effects of views.

I don't think dicts can ever support set methods, since *they aren't 
sets*. Every element consists of both a key and a value, so you have to 
consider both. Set methods are defined in terms of singleton elements, 
not binary elements, so before you even begin, you have to decide what 
does it mean when two elements differ in only one of the two parts?

Given dicts {1: 'a'}, {1: 'b'}, what is the union of them? I can see five 
possibilities:

{1: 'a'}
{1: 'b'}
{1: ['a', 'b']}
{1: set(['a', 'b'])}
Error

Each of the five results may be what you want in some circumstances. It 
would be a stupid thing for dict.union to pick one behaviour and make it 
the One True Way to perform union on two dicts.



-- 
Steven



More information about the Python-list mailing list