6 ms·
> Rather than handing out ready-made functions to make Python behave like PHP, this site actually teaches you how to write Python like a real Pythonista. Not i
by naiquevin 14y ago
> Rather than handing out ready-made functions to make Python behave like PHP, this site actually teaches you how to write Python like a real Pythonista.
Not in my opinion. Here is my personal experience of using this
site when I was just starting with Python. I had landed up there
looking for a function similar to PHP's `array_fill_keys`.
And it showed me `dict.fromkeys(keys, value)`[1] without
a slightest of warning that unexpected things will happen if its
passed a mutable data structure such as an empty list as the
value.
So IMO, for people coming from PHP background writing some of
their first Python code, it can be helpful at times but not an
alternative to learning Python from a book or some serious online
resource. Moreover, the site itself says that it won't teach you
either PHP or Python.[2]
[1]: http://www.php2python.com/wiki/function.array-fill-keys/ http://www.php2python.com/wiki/function.array-fill-keys/
[2]: http://www.php2python.com/about/ http://www.php2python.com/about/
- lloeki 14y agoNot 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)