If the dictionary is a bijection, I use:
{v:k for k,v in d.iteritems()}

Otherwise, I use defaultdict:
d_inv=defaultdict(list)
map(lambda(k,v):d_inv[v].append(k), d.items())

For iso/automorphisms of graphs, I often wish that dictionaries were
both callable and invertible.  In general, yes, I think
DiscreteFunction and DiscreteBijection classes would be very useful.


On Wed, Sep 25, 2013 at 9:08 AM, Nathann Cohen <nathann.co...@gmail.com> wrote:
> Helloooooooo everybody !
>
> I was just messing with dictionaries and lists, and I wonder if we
> could solve the problem once and for all with an inefficient generic
> solution. Here's the thing :
>
> I often have to define both a function, and its inverse. Something like :
>
> d = {
>  'a' : 1,
>  'b' : 2,
>  'c' : 1,
>  'd' : 3
> }
>
> Then, I want to find the list of all elements whose image is a 1, or
> 2, or 3, and end up defining the following dictionary :
>
> d_inv = {
>  1 : ['a','c'],
>  2 : ['b'],
>  3 : ['d']
> }
>
> Aaaaaand it would be sooo nice if there was a way to write d**(-1)[2],
> or something of the kind ! Did you ever write a code like this, and
> would you be interested by a generic tool for that ?
>
> Otherwise I'll just keep on computing the inverse of my dictionaries
> with a couple of Python lines ;-)
>
> Have fuuuuuuuun !
>
> Nathann
>
> --
> You received this message because you are subscribed to the Google Groups 
> "sage-devel" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to sage-devel+unsubscr...@googlegroups.com.
> To post to this group, send email to sage-devel@googlegroups.com.
> Visit this group at http://groups.google.com/group/sage-devel.
> For more options, visit https://groups.google.com/groups/opt_out.

-- 
You received this message because you are subscribed to the Google Groups 
"sage-devel" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sage-devel+unsubscr...@googlegroups.com.
To post to this group, send email to sage-devel@googlegroups.com.
Visit this group at http://groups.google.com/group/sage-devel.
For more options, visit https://groups.google.com/groups/opt_out.

Reply via email to