Best way to deal with different data types in a list comprehension

Chris Kaynor ckaynor at
Wed Sep 24 00:17:22 CEST 2014

On Tue, Sep 23, 2014 at 3:01 PM, Larry Martell <larry.martell at>

> I have some code that I inherited:
> ' '.join([self.get_abbrev()] +
>            [str(f['value')
>             for f in self.filters
>             if f.has_key('value')]).strip()

> This broke today when it encountered some non-ascii data.

One option would be to do the processing in unicode, and convert to utf-8
only when needed:

u' '.join([self.get_abbrev()] +
            for f in self.filters
            if f.has_key('value')]).strip()

If needed, add a .encode('utf-8') to the end.

> I changed the str(f['value']) line to f['value'].encode('utf-8'),
> which works fine, except when f['value'] is not a string (it could be
> anything).
> Without rewriting this without the list comprehension, how can I write
> this to deal with both strings and non-strings?
> --
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list