6 ms·
dic = {k: v for k, v in dic.items() if k in other_dic and v == "bar"} How could that be improved? That's 3-4 LOC minimum in any other language My main grip is
by genidoi 7y ago
dic = {k: v for k, v in dic.items() if k in other_dic and v == "bar"}
How could that be improved? That's 3-4 LOC minimum in any other language
My main grip is python's ternary operators, since the True value is evaluated before the condition, if you are doing ternaries on things that might throw exceptions the False value has to come first
value = 0 if key not in dic else dic[key] * 5
rather than (throws indexerror if key isn't in dic)
value = dic[key] * 5 if key in dic else 0
- grzm 7y agodic = {k: v for k, v in dic.items() if k in other_dic and v == "bar"} > "How could that be improved? That's 3-4 LOC minimum in any other language" If I'm understanding the comprehension correctly, (into {} (filter (fn [[k v]] (and (get other-dic k) (= v "bar"))) dic)) Though, for readability, I'd likely write it as: (->> dic (filter (fn [[k v]] (and (get other-dic k) (= v "bar")))) (into {})) Legibility is in the eye of the beholder.
- genidoi 7y agoEach to their own, but both the snippets you posted crossed my threshold for headache inducing parentheses tracking
- grzm 7y agoSimilarly, my parsing of special-case syntax in the Python.
- genidoi 7y agoWhat special-case syntax? The only brazenly pythonic thing in there was the (iterative) tuple unpacking, as in (for) k, v in dic.items() which is just k, v = (<key>, <value>) for every key value pair in the dictionary
- grzm 7y agoThere are a number of precedence rules you need to keep track of to parse the list comprehension. There are two different syntaxes that do the same thing. Arguably you need to do the same if you don't already know how the threading macro in the my second example works. I posted due to your claim regarding all other languages necessitating increased verbosity. I should have left it lie, as I didn't intend to promote a language war, just to post a counter example. My apologies.
- genidoi 7y agoNo language war intended, just curious how something I see as a wheel could be improved.
- pryffwyd 7y agoIt appears textually first but the evaluation order is the same as the classic ?: ternary. ```[][0] if False else 'foo'``` will not raise an IndexError.
- 1wd 7y agoI like comprehensions, but think this style has some advantages (and some disadvantages): dic = dic.where((k, v) => k in other_dic and v == "bar").todict()
- fiedzia 7y ago> dic = {k: v for k, v in dic.items() if k in other_dic and v == "bar"} dic.iter().filter(|k, v| other_dic.contains(k) && v == "bar").collect(); it's one line, though I'd format it as 3 for readability (list comprehension is hard to read and functional style composes better.