[Python-ideas] [Python-Dev] hello, new dict addition for new eve ?

Nathan Rice nathan.alexander.rice at gmail.com
Tue Jan 3 21:37:42 CET 2012


On Tue, Jan 3, 2012 at 1:45 PM, Robert Kern <robert.kern at gmail.com> wrote:
> On 1/3/12 5:39 PM, Nathan Rice wrote:
>> I haven't had any problems with using set(somedict.items()).  I will
>> admit that I primarily do this in simple contexts.
>>
>> This brings me to another curiosity... Why do mutable items not
>> implement hash using id()?
>
>
> Usually because they do not implement __eq__ using id(). The invariant that
> needs to be maintained is that if two objects compare equal, then they need
> to hash equal. Many mutable objects compare by value, and thus two
> non-identical objects can compare equal.

Ok.  I missed that invariant in the data model (and a couple of other
places, apparently).  Thanks.

>>> Further, you cannot treat dicts as sets of (key, value) pairs because
>>> dicts
>>> have unique keys, not unique (key, value) pairs.
>>
>>
>> I'm confused.  Because keys are unique, (key, value) pairs are unique
>> as well.  I realize the values are not unique but the tuple is
>> guaranteed to be.
>
>
> Yes, the dict.items() would be a valid, unique set, but set operations on
> those sets may not give valid dicts because the same key could point to
> different values in the two dict operands. For example:
>
> [~]
> |7> a = {'one': 1}
>
> [~]
> |8> b = {'one': '1'}
>
> [~]
> |9> set(a.items()) | set(b.items())
> set([('one', '1'), ('one', 1)])
>
> [~]
> |10> dict(set(a.items()) | set(b.items()))
> {'one': 1}
>
> You've lost a value there.

I have been following the earlier discussion of + in the context of
dictionaries, and I agree that many operators do not cleanly map over.
 It seems to me that the comparison operators are well behaved in this
regard though.

As an additional aside, perhaps the return type of elements in the
items call could be made into a nice "Item" namedtuple.  I always
unpack my items into (k, v) or something similar when possible, but
some people aren't as considerate.  Having item.key and item.value
available (and used in examples) encourages nice code; even if someone
chose a horrible name for their items() unpacking, it is easier to
grok "badname.key ... badname.value" than "badname[0] ... badname[1]".

Nathan



More information about the Python-ideas mailing list