Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Not to mention the idiomatic way might just be one of:

    # before generator expressions (generates intermediate list)
    result = dict([ (k, value) for k in keys ])
    
    # with generator expressions (lazy iteration)
    result = dict((k, value) for k in keys)
    
    # with dict comprehension (brand new, probably the fastest)
    result = { k: value for k in keys }


    d = dict.fromkeys(keys, value)
is fine if value is immutable e.g., a string, number.

Your code doesn't solve the mutability problem (each value is the exact same object. If you modify it for one key; the values are modified for all keys).

For a mutable type you need to create a new value for each key:

    d = {k: [] for k in keys}


This works fine too,

   dict((k, []) for k in keys)
Although I later realized what I really needed was defaultdict[1]

   d = defaultdict(list)
[1]: http://docs.python.org/2/library/collections.html#collection...


> Your code doesn't solve the mutability problem

I know that, but I willfully replicated the original code behavior and made it idiomatic (which has the advantage of making it both obvious and easily adjustable)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: