Re: Eliminate "extra" variable

Discussion in 'Python' started by Tim Chase, Dec 8, 2013.

  1. Tim Chase

    Tim Chase Guest

    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)

    -tkc
    Tim Chase, Dec 8, 2013
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Igor Korot

    Eliminate "extra" variable

    Igor Korot, Dec 6, 2013, in forum: Python
    Replies:
    0
    Views:
    52
    Igor Korot
    Dec 6, 2013
  2. Peter Otten

    Re: Eliminate "extra" variable

    Peter Otten, Dec 8, 2013, in forum: Python
    Replies:
    0
    Views:
    77
    Peter Otten
    Dec 8, 2013
  3. Tim Chase

    Re: Eliminate "extra" variable

    Tim Chase, Dec 8, 2013, in forum: Python
    Replies:
    0
    Views:
    71
    Tim Chase
    Dec 8, 2013
  4. Mark Lawrence

    Re: Eliminate "extra" variable

    Mark Lawrence, Dec 8, 2013, in forum: Python
    Replies:
    14
    Views:
    121
    Igor Korot
    Dec 16, 2013
  5. Tim Chase

    Re: Eliminate "extra" variable

    Tim Chase, Dec 8, 2013, in forum: Python
    Replies:
    0
    Views:
    58
    Tim Chase
    Dec 8, 2013
Loading...

Share This Page