3 ms·
Not to mention the idiomatic way might just be one of: # before generator expressions (generates intermediate list) result = dict([ (k, value) for k in
by lloeki 14y ago
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 }
- d0mine 14y agod = 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}
- naiquevin 14y agoThis 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#collections.defaultdict http://docs.python.org/2/library/collections.html#collection...
- lloeki 14y ago> 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)