1

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
  • 2
    What happens when multiple keys have the value barfoo?
    – muru
    Nov 13, 2018 at 3:37
  • @muru In my case the keys and values were unique and guaranteed to not have duplicates. Nov 13, 2018 at 3:41

2 Answers 2

4

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
1
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

5
  • 1
    you might want to copy the dict to prevent it from being changed accidentally 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
    Nov 13, 2018 at 7:47
  • @muru I am not sure this is true 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
    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 Nov 13, 2018 at 10:49

Your Answer

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

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