4 ms·
in python: >>> from collections import defaultdict >>> map = defaultdict(int) >>> for word in ['hi', 'there', 'hi']: ... map[word] += 1 I am
by wcarss 8y ago
in python:
>>> from collections import defaultdict
>>> map = defaultdict(int)
>>> for word in ['hi', 'there', 'hi']:
... map[word] += 1
I am glad Java has this stuff now, but it's a little surprising that its tools are still so obtuse relative to competitors.
edit: I should have foreseen the derailment caused by and nitpicking to follow a comment like this. Sorry folks!
- kbsletten 8y agoTo be fair, getValueOrDefault is strictly more powerful than defaultdict because you can vary the initial value by the key.
- detaro 8y agodict.get() does the same in Python (optional second parameter for a default value). But I've wondered too why there isn't a form of the default dict that can take parameters like the key for the factory function.
- nayuki 8y agoFunny you say that, because I find the key-sorted TreeMap to be useful in Java, but Python seems to have no equivalent.
- tgb 8y agoYou'd preferably use collections.Counter for this.
- meddlepal 8y agoYes... now turn that map into a lock free thread-safe dict in Python and show us the same code. I get that for free in Java via ConcurrentHashMap.
- ben-schaaf 8y agoIf you mean lock-free as in no GIL, you obviously can't. But otherwise all python code is inherently thread safe.
- meddlepal 8y agoYea I meant lock free and ready for multi-threaded use without a GIL. I didn't mean to dump on Python either, I write a lot of Python and Java but comparisons like yours aren't really fair because the JVM is just considerably more powerful than Python's runtime. I could take a huge list of words, hand subsets to threads and let them all update the same map using the same API and without needing a lock.
- mruts 8y agoBut your python code is still really ugly. In Scala: import scala.collection.mutable.Map > val map = Map.empty[String, Int] > List("hi", "there", "hi").map { x => > map(x) = i > }
- virtualwhys 8y agoNot the same but immutable approach is more idiomatic Scala. List("hi", "there", "hi") .zipWithIndex .map { case (x, i) => x -> i }.toMap
- mruts 8y agoThat example doesn’t really illustrate the point of updating maps with repeated values.