On Thursday 22 July 2010 09:36 PM, Anand Balachandran Pillai wrote:
On Thu, Jul 22, 2010 at 7:00 PM, steve<st...@lonetwin.net>  wrote:

Hi,


On 07/22/2010 05:02 PM, Anand Balachandran Pillai wrote:

On Thu, Jul 22, 2010 at 3:21 PM, Vikram<kp...@rediffmail.com>   wrote:

   Suppose you have the following list:
  >>>   x =[['cat',10],['cat',20],['cat',30],['dog',5],['dog',1],['dog',3]]

  My problem is that i wish to obtain the following two dictionaries:
  xdictstart = {'cat':10, 'dog':1}
  xdictend = {'cat':30, 'dog':5}


   Any nice way to do the above? Thanks.

  Yes. Try this.
   x =[['cat',10],['cat',20],['cat',30],['dog',5],['dog',1],['dog',3]]
  x.sort()
  xdictstart = dict(reversed(x))
  xdictend = dict(x)
  xdictstart,xdictend

({'dog': 1, 'cat': 10}, {'dog': 5, 'cat': 30})
Are you sure that'll work ? Is creating a dict from a sequence guaranteed
to be executed serially withing the sequence ?

Yes, it is. Since the list is sorted, the entries are entered into the
dictionary
serially (list is ordered), so hence in normal order we find the larger
value
overwrites the others and in reversed order, the smaller value.

  I cannot think of a solution which is shorter than this.

Out of curiosity I tried benchmarking few of these solutions alongwith the one I wrote using itertools.groupby.
My benchmarking did include large data sets and worst case.
Results are the shortest solution (by Anand) was way faster than others. After that it was Steve's and mine and Navin was almost the same of the last spot.

Which one is most readable? Well I leave that for now.

Shekhar
_______________________________________________
BangPypers mailing list
BangPypers@python.org
http://mail.python.org/mailman/listinfo/bangpypers

Reply via email to