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
    Commented Nov 13, 2018 at 3:37
  • @muru In my case the keys and values were unique and guaranteed to not have duplicates. Commented Nov 13, 2018 at 3:41

2 Answers 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

echo g:mykey
  • Thats exactly what I need! thanks for this! Commented Nov 13, 2018 at 5:22

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 Commented Nov 13, 2018 at 7:38
  • @ChristianBrabandt but if you copy it, it would no longer be more efficient than simply looping over it, right?
    – muru
    Commented Nov 13, 2018 at 7:47
  • @muru I am not sure this is true Commented Nov 13, 2018 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
    Commented Nov 13, 2018 at 8:05
  • Even after a copy it s usually faster. Loops are really slow :(. Thanks for the reminder, i'll fix my answer Commented Nov 13, 2018 at 10:49

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.