Python `collections.ChainMap` equivalent?

Python’s collections.ChainMap class groups multiple dicts or other mappings together to create a single, updateable view. So it is suitable to let user-specified command-line arguments take precedence over environment variables by collections.ChainMap:

import builtins
pylookup = ChainMap(locals(), globals(), vars(builtins))
import os, argparse

defaults = {'color': 'red', 'user': 'guest'}

parser = argparse.ArgumentParser()
parser.add_argument('-u', '--user')
parser.add_argument('-c', '--color')
namespace = parser.parse_args()
command_line_args = {k:v for k, v in vars(namespace).items() if v}

combined = ChainMap(command_line_args, os.environ, defaults)

Is there a Julia equivalent to ChainMap?

It looks like you’re looking for functionality to merge two Dicts. The most straight-forward way to do this is probably the merge function, which you can call on multiple Dicts. Note however, that this creates a whole new dictionary, which is slightly different to what python does, so depending on your use case, performance scaling might differ. If you want exactly the same behavior as the python version, this could probably also be implemented pretty easily

1 Like

There also is a merge! function if you want to merge things in place.

LayerDicts.jl seems to do the job if you only need read


Exactly what I want, thank you!