[Tutor] dictionary values

Kent Johnson kent37 at tds.net
Sat Jul 9 03:09:04 CEST 2005


Brian van den Broek wrote:
> 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

Hmm, list comprehension is your friend... how about
  min_val = min(a_dict.values())
  low_keys = [ k for k,v in a_dict.items() if v == min_val ]

More concise and IMO much more readable.

Kent



More information about the Tutor mailing list