9

I have two dicts:

:let defaults = {'hello': 'world', 'bye': 'jupiter'}

:let override = {'hello': 'mars'}

How can I merge the keys from override so that I end up with a new dict like so:

{'hello': 'mars', 'bye': 'jupiter'}
7

You can use extend():

:let defaults = {'hello': 'world', 'bye': 'jupiter'}
:let override = {'hello': 'mars'}

:echo extend(defaults, override)
{'hello': 'mars', 'bye': 'jupiter'}

Keys from the second argument override any existing ones in the first. The defaults dict will be modified in place, which may not be wanted. Use copy() to prevent that:

:call extend(copy(defaults), override)
:echo defaults
{'hello': 'world', 'bye': 'jupiter'}

This is especially something to be careful of when you're passing a dict to a function, since it's passed by reference (so it'll be modified outside of the function, too).


Note that it's won't merge nested dicts, which may or may not be a good thing, depending on what you're looking for:

:echo extend({'nest': {'a': 'b'}}, {'nest': {'b': 'XXXX'}})
{'nest': {'b': 'XXXX'}}

You'll need a small helper function to recursively merge nested dicts:

" Merge two dictionaries, also recursively merging nested keys.
"
" Use extend() if you don't need to merge nested keys.
fun! s:merge(defaults, override) abort
  let l:new = copy(a:defaults)
  for [l:k, l:v] in items(a:override)
    let l:new[l:k] = (type(l:v) is v:t_dict && type(get(l:new, l:k)) is v:t_dict)
          \ ? s:merge(l:new[l:k], l:v)
          \ : l:v
  endfor
  return l:new
endfun

You can remove the copy() if you want to modify it in-place (bit faster, but possibly unexpected).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.