Python - Filtering Dicts
I’ve been needing to do some Python for work lately. Nothing big or fancy, but it does involve working with lists and dicts… Coming from Elixir and Ruby I can’t help but wonder if I’m missing some greater point about how Python does this stuff. Like, why does filtering a dict not return a dict but has to be cast into one? And why are items treated like tuples in the comprehension/lambda? I know the underlying form is most likely a tuple in both Python, Elixir and Ruby, but I don’t really care to be dealing directly with it.
Like, this stuff, for instance, in Python:
d = {'foo': 1, 'bar': 2, 'baz': 3}
dict(filter(lambda x: x[0] in ['bar', 'baz'], d.items()))
# => {'bar': 2, 'baz': 3}
In Elixir:
m = %{foo: 1, bar: 2, baz: 3}
m |> Map.take([:bar, :baz])
# => %{bar: 2, baz: 3}
Or in Ruby:
h = {foo: 1, bar: 2, baz: 3}
h.slice(:bar, :baz)
# => {:bar=>2, :baz=>3}
I mean, if I want, I can make both the Elixir and Ruby examples as low-level and complex as the Python example — both languages have filtering methods similar to the Python one — but filtering keys from a hash/dict/map is such a regular task that I’d expect a modern high-level language to have convenience functions for it. So what is it I’m missing? I haven’t been doing much Python at all, so I’m sure there’s lots of stuff I don’t know and that I’m not aware of.
I’m aware that some languages would be even more verbose and involved (like Go and, I imagine, Rust), but those languages are typically both a lot more opinionated than Python and also markedly different languages with different purposes.