Question about consistency in python language

Bengt Richter bokr at oz.net
Thu Sep 8 21:01:23 EDT 2005


On 8 Sep 2005 16:03:12 -0700, lechequier at gmail.com wrote:

>Let's say I define a list of pairs as follows:
>>>l = [('d', 3), ('a', 2), ('b', 1)]
>
>Can anyone explain why this does not work?
>>>h = {}.update(l)
>
>and instead I have to go:
>>>h = {}
>>>h.update(l)
>to initialize a dictionary with the given list of pairs?
>
>when an analagous operation on strings works fine:
>>>s = "".join(["d","o","g"])
>
>Seems inconsistent. 
>
Join isn't that good an analogy, because the inputs and outputs are immutable.
list.sort is more comparable to dict.update. There is now a builtin sorted function
that will take a list and return a sorted one. Perhaps there will come an "updated"
function analogously for dictionaries, but I don't think the use is that common,
and you can make your own. Several ways. If you want to start with an empty dict
anyway, the dict constructor will accept a sequence of pairs (so long as the first
of every pair is hashable, which is also required for update). E.g.,

 >>> dict([('d', 3), ('a', 2), ('b', 1)])
 {'a': 2, 'b': 1, 'd': 3}

or the sequence of pairs as a tuple expression
 >>> dict((('d', 3), ('a', 2), ('b', 1)))
 {'a': 2, 'b': 1, 'd': 3}

or sometimes it's handy to start with the keys and values as separate sequences
and zip them together for the dict constructor

 >>> dict(zip('dab', [3,2,1]))
 {'a': 2, 'b': 1, 'd': 3}

or a generator expression

 >>> dict((k,3-i) for i,k in enumerate('dab'))
 {'a': 2, 'b': 1, 'd': 3}


though note that dict wants the sequence as a single argument:
 >>> dict( ('d', 3), ('a', 2), ('b', 1) )
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 TypeError: dict expected at most 1 arguments, got 3

 >>> def updated(d, seq): d=d.copy(); d.update(seq); return d
 ...
 >>> updated({}, [('d', 3), ('a', 2), ('b', 1)])
 {'a': 2, 'b': 1, 'd': 3}

One rationale for not returning a reference to the mutated value
from a mutating method is that it is too easy to think of it
as a pure expression, and forget the persistent side effect of
mutating the object. I think that was thought too bug-prone.

Regards,
Bengt Richter



More information about the Python-list mailing list