Eliminate "extra" variable

Tim Chase python.list at tim.thechases.com
Sun Dec 8 19:58:20 CET 2013

On 2013-12-08 15:04, Peter Otten wrote:
> >     data = dict(
> >       (str(date), {source: freq})
> >       for date, freq, source in original_data
> >       )  
> or even just
> data = {str(date): {source: freq}
>         for date, freq, source in original_data}

I maintain enough pre-2.7 code that I tend to eschew
dict-comprehensions for the time being.  I like them as a language
addition, but can't use them yet in most of the code-bases with which
I work.  To the OP, if you don't have to support pre-2.7 code, then
this is a tidier way to go.

> But do you really need a dict with a single key? And is it even
> correct? If a date occurs twice only the last source:freq pair is
> kept. Without knowing the context the humble
> data = {}
> for date, freq, source in original_data:
>     source_to_freq = data.setdefault(date, {})
>     if source in source_to_freq:
>         raise ValueError(
>             "Multiple frequencies for one source not supported")
>     source_to_freq[source] = freq
> appears so much more plausible...

The OP's code didn't do any such sanity-checking so I made the
assumption that the data came in clean.  I know better than to trust
incoming data (even my own) in my own code, but...

(followup to the OP's reply elsewhere in the thread coming shortly)


More information about the Python-list mailing list