[BangPypers] list problem
Baishampayan Ghose
b.ghose at gmail.com
Thu Jul 22 13:28:16 CEST 2010
> 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.
Don't know if this is nice, but I might want to solve this problem in
Python like this -
###
from collections import defaultdict
items = [['cat', 10], ['cat', 20], ['cat', 30], ['dog', 5], ['dog',
1], ['dog', 3]]
item_values = defaultdict(list) # this makes the values of this dict
lists by default
starts = {}
ends = {}
for k, v in items:
item_values[k].append(v)
for k in item_values:
starts[k] = min(item_values[k])
ends[k] = max(item_values[k])
print starts, ends
###
Feedback appreciated.
Regards,
BG
--
Baishampayan Ghose
b.ghose at gmail.com
More information about the BangPypers
mailing list