0

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?

  • 2
    What happens when multiple keys have the value barfoo? – muru Nov 13 '18 at 3:37
  • @muru In my case the keys and values were unique and guaranteed to not have duplicates. – John Fred Fadrigalan Nov 13 '18 at 3:41
2

There'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
5

echo keys(filter(copy(dict), 'index(v:val, "foobar")>=0'))[0] should do it

Note it'll be much more efficient than a loop

  • 1
    you might want to copy the dict to prevent it from being changed accidentally – Christian Brabandt Nov 13 '18 at 7:38
  • @ChristianBrabandt but if you copy it, it would no longer be more efficient than simply looping over it, right? – muru Nov 13 '18 at 7:47
  • @muru I am not sure this is true – Christian Brabandt Nov 13 '18 at 8:00
  • 1
    @ChristianBrabandt how so? If the goal is to prevent accidental modification, you'd need a full deep copy, and that cannot be faster than simply iterating over a view of those items. – muru Nov 13 '18 at 8:05
  • Even after a copy it s usually faster. Loops are really slow :(. Thanks for the reminder, i'll fix my answer – Luc Hermitte Nov 13 '18 at 10:49

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.