5

I am wondering if it possible to short circuit the check for the existence of a key in a dict and an immediatly following assignment to a variable with that key if it exists. That is, if the following code can be abbreviated to something like let s:val = s:tq84_dict['foo'] || 'default' (which won't work in vim script)

if has_key(s:tq84_dict, 'foo')
  let s:val = s:tq84_dict['foo']
else
  let s:val = 'default'
endif

1 Answer 1

9

Use the get() function:

:echo get({}, 'foo', 'default')
default

:echo get({'foo': 'it is set'}, 'foo', 'default')
it is set

If you're familiar with Python, this is the same as {}.get('foo', 'default').

Another way would be to use the ternary if:

:let dict = {}
:let val = has_key({}, 'foo') ? dict['foo'] : 'default'
:echo val
default

:let dict = {'foo': 'it is set'}
:let val = has_key(dict, 'foo') ? dict['foo'] : 'default'
:echo val
it is set

But in this case get() is clearly the better way to do it.

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.