[Tutor] dictionary values

Brian van den Broek bvande at po-box.mcgill.ca
Sat Jul 9 02:34:26 CEST 2005


luke p said unto the world upon 08/07/2005 19:40:
> 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.
> 
> what I will do instead to find the lowest is just use a list instead...
> 
> alphalist = ['a','b' ... 'z']
> alphavalues = [0,0 ... 0]
> lowest = alphavalues[0]
> lowestlocation = 0
> and just do
> for x in range(26):#or is it 25? can't remember if value is included
>   if alphavalues[x] < lowest:
>     lowest = alphavalues[x]
>     lowestlocation = x
> 
> but for future reference I just wondered about the dictionary thing.
> thanks in advance.
> -Luke


Hi Luke,

if you care about the possibility that there is no unique key with the 
lowest value, I'd do:

 >>> def get_low_keys(a_dict):
... 	'''-> list of keys in a_dict with lowest value'''
... 	min_val = min(a_dict.values())
... 	low_keys = []
... 	for k,v in a_dict.items():
... 		if v == min_val:
... 			low_keys.append(k)
... 	return low_keys
...
 >>> lows = get_low_keys(my_dict)
 >>> lows
['another one', 'one']
 >>>

If you don't care abut duplicate values, then:

 >>> def get_low_key(a_dict):
... 	'''a key in a_dict with lowest value'''
... 	min_val = min(a_dict.values())
... 	for k,v in a_dict.items():
... 		if v == min_val:
... 			return k
...
 >>> low = get_low_key(my_dict)
 >>> low
'another one'

HTH,

Brian vdB




More information about the Tutor mailing list