16

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'}

1 Answer 1

15

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).

2
  • Instead of extend(copy(defaults), override) you can use extendnew(defaults, override). Details.
    – Shamaoke
    Jun 9, 2023 at 10:52
  • That didn't exist yet when I wrote this @Shamaoke; I prefer to keep it as-is for now, as many people are running old Vim versions from their distro and extendnew() is "only" 2 years old, and an extra copy() an extra copy() is just a few more extra characters. Jun 9, 2023 at 14:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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