dict invert - learning question

Duncan Booth duncan.booth at invalid.invalid
Sat May 3 16:51:41 EDT 2008


dave <squareswallower at y1a2hoo3.com> wrote:

> Hello,
> 
> here is a piece of code I wrote to check the frequency of values and 
> switch them around to keys in a new dictionary.  Just to measure how 
> many times a certain key occurs:
> 
> def invert(d):
>      inv = {}
>      for key in d:
>           val = d[key]
>           if val not in inv:
>                inv.setdefault(val, [key])
>           else:
>                inv[val].append(key)
>      return inv
> 
> 
> Using the methods above (I'm just a beginner) could I have written it 
> more concisely?  Any criticism/critique in the code would be greatly 
> appreciated.
> 
The obvious change I'd make is:


     if val not in inv:
         inv[val] = key
     else:
         ... etc.

The setdefault method is only appropriate if you don't know 
whether or not the key is in the dictionary. since you've already tests 
that you should just go ahead and set the value.
Otherwise it all seems fine.



More information about the Python-list mailing list