2 ms·
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 s
by d0mine 14y ago
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}
- 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)