[Tutor] dictionary values
Kent Johnson
kent37 at tds.net
Sat Jul 9 03:03:25 CEST 2005
luke p wrote:
> just assume all the below code is correct.
> I am not having a problem with it, it is all for example only.
>
> I have a dictionary like this:
> alpha = {'a':0,'b':0, ... 'z':0}
> and the following code
> f = file("hamlet.txt","r")
> text = f.readlines()
> f.close()
> for line in text:
> for char in line:
> try:
> alpha[char] += 1
>
> so at the end of the loop I have a dictionary eg.
> {'a':14000,'b':12000 ... 'z':100}
>
> what I want to do is find out which value in my dictionary is lowest.
> is there a dictionary function for this, like alpha.min() that will
> return a key:value pair of the lowest? I cannot find one and I
> wondered if there was a quick fix to this.
It's easy enough to convert the dictionary to a list of (count, letter) pairs and find the min of the list:
>>> alpha = {'a':14000,'b':12000, 'z':100}
>>> alpha.items()
[('a', 14000), ('b', 12000), ('z', 100)]
>>> [(v,k) for k,v in alpha.items()]
[(14000, 'a'), (12000, 'b'), (100, 'z')]
>>> min([(v,k) for k,v in alpha.items()])
(100, 'z')
or in Python 2.4, without creating the intermediate lists:
>>> min((v,k) for k,v in alpha.iteritems())
(100, 'z')
Kent
More information about the Tutor
mailing list