dict invert - learning question

Jerry Hill malaclypse2 at gmail.com
Sat May 3 22:25:32 EDT 2008


On Sat, May 3, 2008 at 4:29 PM, dave <squareswallower at y1a2hoo3.com> wrote:
>  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.

If you're using python 2.5, the collections module has the defaultdict
type that is useful for things like this.

from collections import defaultdict

def invert2(d):
    inv = defaultdict(list)
    for key, value in d.items():
        inv[value] += key
    return dict(inv)

If you don't mind returning a defaultdict instead of a regular
dictionary, you could just 'return inv'.  The defaultdict is useful
for building up the frequency counts in the first place too:

def wordcount(wordlist):
    wc = defaultdict(int)
    for word in wordlist:
        wc[word] += 1
    return dict(wc)


-- 
Jerry



More information about the Python-list mailing list