[Python-Dev] Re: A small proposed change to dictionaries' "get"
method
M.-A. Lemburg
mal@lemburg.com
Thu, 03 Aug 2000 12:11:24 +0200
"Barry A. Warsaw" wrote:
>
> >>>>> "GM" == Gareth McCaughan <Gareth.McCaughan@pobox.com> writes:
>
> GM> Consider the following piece of code, which takes a file
> GM> and prepares a concordance saying on which lines each word
> GM> in the file appears. (For real use it would need to be
> GM> made more sophisticated.)
>
> | line_number = 0
> | for line in open(filename).readlines():
> | line_number = line_number+1
> | for word in map(string.lower, string.split(line)):
> | existing_lines = word2lines.get(word, []) |
> | existing_lines.append(line_number) | ugh!
> | word2lines[word] = existing_lines |
>
> I've run into this same situation many times myself. I agree it's
> annoying. Annoying enough to warrant a change? Maybe -- I'm not
> sure.
>
> GM> I suggest a minor change: another optional argument to
> GM> "get" so that
>
> GM> dict.get(item,default,flag)
>
> Good idea, not so good solution. Let's make it more explicit by
> adding a new method instead of a flag. I'll use `put' here since this
> seems (in a sense) opposite of get() and my sleep addled brain can't
> think of anything more clever. Let's not argue about the name of this
> method though -- if Guido likes the extension, he'll pick a good name
> and I go on record as agreeing with his name choice, just to avoid a
> protracted war.
>
> A trivial patch to UserDict (see below) will let you play with this.
>
> >>> d = UserDict()
> >>> word = 'hello'
> >>> d.get(word, [])
> []
> >>> d.put(word, []).append('world')
> >>> d.get(word)
> ['world']
> >>> d.put(word, []).append('gareth')
> >>> d.get(word)
> ['world', 'gareth']
>
> Shouldn't be too hard to add equivalent C code to the dictionary
> object.
The following one-liner already does what you want:
d[word] = d.get(word, []).append('world')
... and it's in no way more readable than your proposed
.put() line ;-)
--
Marc-Andre Lemburg
______________________________________________________________________
Business: http://www.lemburg.com/
Python Pages: http://www.lemburg.com/python/