Sorting distionary by value
Steven Majewski
sdm7g at Virginia.EDU
Thu Mar 28 12:27:56 EST 2002
On Thu, 28 Mar 2002, phil hunt wrote:
> On Wed, 27 Mar 2002 23:02:20 -0500, Peter Hansen <peter at engcorp.com> wrote:
> >Jim Dennis wrote:
> >>
> >> The core loop is something like:
> >>
> >> freq = {}
> >> for line in file:
> >> for word in line.split():
> >> if word in freq: freq[word] += 1
> >> else: freq[word] = 1
> >>
> >> (assuming Python2.2 for file interation and dictionary membership
> >> support using "in." I *really* like those 2.2 features! They make
> >> my psuedo-code so executable!)
> >
> >Something like freq[word] = freq.get(word, 0) + 1
> >
> >would probably be faster, and it's a little simpler I think,
> >although I could see an argument that it's less readable.
> >Also doesn't depend on 2.2.
>
> IIRC in Awk you can just say: freq[word] ++ and it works
> correctly even when there is no pre-existing index of word in freq.
>
> IMO it's a pity Python isn't like that.
>
However, with 2.2 you can do something like this to give key
access a default value:
Python 2.2.1c1 (#1, Mar 19 2002, 02:06:22)
[GCC 2.95.2 19991024 (release)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class Dcounter(dict):
... default = 0
... def __getitem__( self, key ):
... return self.get( key, self.default )
...
>>>
>>> count = Dcounter( {'ten':10, 'nine':9 } )
>>> count['ten']
10
>>> count['one'] += 1
>>> count['one']
1
>>> count['two'] += 1
>>> count['two'] += 1
>>> count['two']
2
>>> count
{'nine': 9, 'two': 2, 'ten': 10, 'one': 1}
>>> count['zero']
0
-- Steve Majewski
More information about the Python-list
mailing list