Suppose I have a dictionary declared like this:
g:dict = {
\ 'foo' : ['foobar'],
\ 'bar' : ['barfoo']
\}
how can I get the key for barfoo
using just the value(barfoo
) itself?
Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It only takes a minute to sign up.
Sign up to join this communityThere's no function to get a dictionary key from a value, so you'll have to loop over the keys. For example:
for [key, value] in items(g:dict)
if index(value, "barfoo") >= 0
let g:mykey = key
break
endif
endfor
echo g:mykey
echo keys(filter(copy(dict), 'index(v:val, "foobar")>=0'))[0]
should do it
Note it'll be much more efficient than a loop
copy
the dict to prevent it from being changed accidentally
Nov 13, 2018 at 7:38
barfoo
?