Stream: helpdesk (published)

Topic: Map over dictionary, preserving container type


view this post on Zulip Evan Patterson (Oct 19 2021 at 05:19):

A nice feature of map is that it preserves the container type while potentially changing the element type. For example, if you map over a Vector, you get back a Vector, and if you map over a StaticVector, you get back another StaticVector. This is a good reason to prefer map over list comprehensions in some cases.

I'd like the same thing, but for dictionaries. Here's what I'm currently doing. I define a helper function

roottype(T) = T isa UnionAll ? T : T.name.wrapper

and then I write something like

mapvals(f, d::D) where D = (roottype(D))(k => f(v) for (k,v) in d)

This seems to work but it feels bad. Is there a better way?

view this post on Zulip Kwaku Oskin (Oct 19 2021 at 08:31):

Have you seen Dictionaries.jl?

view this post on Zulip Evan Patterson (Oct 19 2021 at 16:29):

It looks very nice, but it's a replacement for the standard dictionary types, right? I was looking for something that would work with Dict, OrderedDict, and other AbstractDict types.

view this post on Zulip Mason Protter (Oct 19 2021 at 16:35):

This would be a nice thing to have. I can’t really think of away to do it other than what you’ve suggested though unfortunately.

view this post on Zulip Expanding Man (Oct 19 2021 at 16:36):

I find the situation with Dictionaries.jl rather frustrating. I agree it is better than Base dictionaries, but so much is already designed to use Base dictionaries that I am hesitant to use it.

view this post on Zulip Evan Patterson (Oct 19 2021 at 16:39):

That is my feeling as well.


Last updated: Dec 28 2024 at 04:38 UTC