[BangPypers] list problem

Shashwat Anand anand.shashwat at gmail.com
Thu Jul 22 16:00:54 CEST 2010


On Thu, Jul 22, 2010 at 3:21 PM, Vikram <kpguy at 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.
>

How about this :
>>> x
[['cat', 10], ['cat', 20], ['cat', 30], ['dog', 5], ['dog', 1], ['dog', 3]]

Remove duplicates for key pair of dictionary.
>>> keys = list(set(i[0] for i in x))
>>> keys
['dog', 'cat']

Now for every unique keys  make a list containing all the items for that
key.
>>> [sorted([i for i in x if i[0]==k], key=operator.itemgetter(1)) for k in
keys]
[[['dog', 1], ['dog', 3], ['dog', 5]], [['cat', 10], ['cat', 20], ['cat',
30]]]

You can now easily create dictionary.
>>> xdictstart = dict(i[0] for i in [sorted([i for i in x if i[0]==k],
key=operator.itemgetter(1)) for k in keys])
>>> xdictstart
{'dog': 1, 'cat': 10}
>>> xdictend = dict(i[-1] for i in [sorted([i for i in x if i[0]==k],
key=operator.itemgetter(1)) for k in keys])
>>> xdictend
{'dog': 5, 'cat': 30}

The benefit is you can make a complete dictionary if you want, not only
start and end values.


> -------
> Those interested in the above problem may consider the following code
> (which does not actually do what i want):
>
> >>> xdictend = dict(x)
> >>> xdictend
> {'dog': 3, 'cat': 30}
>
> >>> x
> [['cat', 10], ['cat', 20], ['cat', 30], ['dog', 5], ['dog', 1], ['dog', 3]]
> >>> xdictstart = {}
> >>> map(xdictstart.setdefault, *zip(*x))
> [10, 10, 10, 5, 5, 5]
> >>> xdictstart
> {'dog': 5, 'cat': 10}
>
> _______________________________________________
> BangPypers mailing list
> BangPypers at python.org
> http://mail.python.org/mailman/listinfo/bangpypers
>



-- 
~l0nwlf


More information about the BangPypers mailing list