[Python-sets] Dictionary comprehension? [OT?]

Magnus Lie Hetland mlh at idi.ntnu.no
Sun Jun 10 10:28:00 EDT 2001


From: "Tim Peters" <tim.one at home.com>
>
> [Magnus Lie Hetland]
> > I was thinking about the possibility of dictionary
> > comprehension a minute ago (I vaguely recollect doing
> > so before...) and came to think of the set comprehension
> > syntax...
>
> Historical note:  the dict.update() function was argued over for years
> before getting implemented, because it was thought unclear what should
> happen if, in x.update(y), y had a key k already in x.  Should y[k] "win"?
> x[k]?  Should x[k] grow a list of associated values?  Should overlap raise
> an exception?  The same arguments apply to dict comprehensions, of course,
> but I think we have a clearer model here already:
>
> >>> {1:1, 2:2, 1:3}
> {1: 3, 2: 2}
> >>>
>
> That is, "rightmost wins" is already the rule.

Right - that's what my suggestion was for the comprehension too. I've been
thinking about an augmented version as well, but I'm not happy with the
syntax (which is the only one I can think of) - putting an operator
in front of the colon (e.g. +:) would update the entry (by means of that
operator) rather than overwriting it. It is assumed that the identity
element of the operator (0 for +) is put into the slot before updating is
begun... So to invert a dictionary, putting keys with the same value into
a set (assuming they exist) could be done like this:

  reversed = {d[k] +: {k} for k in d}

To make a dictionary of word frequencies from a string, you could do
this:

  freq = {w +: 1 for w in s.split()}

I guess I'm moving into the Dark Side here... Perhaps I should just stick
to for-loops :)


> I have no idea what {v for k in dict} is supposed to mean, so I'm not
> especially concerned about confusing the interpreter in that case <wink>.

<ahem>

Sorry about that one... I gues it would be a singleton set if v is already
defined, right? :)

> The other syntax is natural enough, but I'm not sure it's *useful* enough.

You may be right. As long as we get the dict method taking a list of tuples
we can do it all with list comprehension, I guess. (But the same thing could
be said about set comprehension - why not be consistent? ;)

> Inverting a relation does have to worry about what happens when inverting
a
> many-to-one mapping, and that the order of dict traversal isn't defined
> means that inverting a many-to-one mapping may even yield different
results
> across different releases

As you can see, I addressed that problem above... Albeit in a slightly
non-Pythonic way, I guess.

--

  Magnus Lie Hetland         http://www.hetland.org

 "Reality is that which, when you stop believing in
  it, doesn't go away."           -- Philip K. Dick






More information about the Python-list mailing list