Dict comp help

Oscar Benjamin oscar.j.benjamin at gmail.com
Thu Jan 24 16:11:32 EST 2013


On 24 January 2013 20:58, Joseph L. Casale <jcasale at activenetwerx.com> wrote:
> Hi,
> Slightly different take on an old problem, I have a list of dicts, I need to build one dict
> from this based on two values from each dict in the list. Each of the dicts in the list have
> similar key names, but values of course differ.
>
>
> [{'a': 'xx', 'b': 'yy', 'c': 'zz'},  {'a': 'dd', 'b': 'ee', 'c': 'ff'}]
>
>
> { 'xx': 'zz', 'dd': 'ff'}
>
>
> Anyone have insight on how to pull this off?
>

Your specification is not exactly clear about how to handle all of the
different cases or what you really want but how about:

>>> l = [{'a': 'xx', 'b': 'yy', 'c': 'zz'}, {'a': 'dd', 'b': 'ee', 'c': 'ff'}]
>>> dict(d.values()[:2] for d in l)
{'xx': 'zz', 'dd': 'ff'}


Oscar



More information about the Python-list mailing list