From ba815f9378671d25aa63012c1903d42b771df6e9 Mon Sep 17 00:00:00 2001 From: claudejrogers Date: Sat, 24 Aug 2013 17:00:37 -0700 Subject: [PATCH] Use 'key' kwarg in min/max/sorted when calculating with dicts Instead of zipping the values and keys of a dictionary to sort or find the min/max, why not use the 'key' kwarg of those functions along with dict.items()? --- src/1/calculating_with_dictionaries/example.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/1/calculating_with_dictionaries/example.py b/src/1/calculating_with_dictionaries/example.py index 325e4f5..7943e08 100644 --- a/src/1/calculating_with_dictionaries/example.py +++ b/src/1/calculating_with_dictionaries/example.py @@ -1,6 +1,7 @@ # example.py # # Example of calculating with dictionaries +from operator import itemgetter prices = { 'ACME': 45.23, @@ -11,15 +12,15 @@ } # Find min and max price -min_price = min(zip(prices.values(), prices.keys())) -max_price = max(zip(prices.values(), prices.keys())) +min_price = min(prices.items(), key=itemgetter(1)) +max_price = max(prices.items(), key=itemgetter(1)) print('min price:', min_price) print('max price:', max_price) print('sorted prices:') -prices_sorted = sorted(zip(prices.values(), prices.keys())) -for price, name in prices_sorted: +prices_sorted = sorted(prices.items(), key=itemgetter(1)) +for name, price in prices_sorted: print(' ', name, price)