1

Say i've got two list and wanna make a dict of them; the first one will become keys and the second one will be values:

a = ['a', 'b', 'c']
b = ['foo', 'bar', 'baz']
dict = { 'a':'foo', 'b':'bar', 'c': 'baz' }

How to accomplish this in Viml scripting language? is there any function like zip() in python to achieve this?

dNitro
  • 5,145
  • 2
  • 20
  • 45

1 Answers1

3

You'll have to implement this kind of zip function yourself with a manual loop I'm afraid.

For instance:

function! lh#list#zip_as_dict(l1, l2) abort
  if len(a:l1) != len(a:l2)
    throw "Zip operation cannot be performed on lists of different sizes"
  endif
  let res = {}
  let idx = range(0, len(a:l1)-1)
  for i in idx
    let res[a:l1[i]] = a:l2[i]
  endfor
  return res
endfunction

Note that it can also be done without a manual loop thanks to map() + extend(). It should be slightly faster on big lists.

function! lh#list#zip_as_dict(l1, l2) abort
  call lh#assert#equal(len(a:l1), len(a:l2),
        \ "Zip operation cannot be performed on lists of different sizes")
  let res = {}
  call map(range(len(a:l1)), 'extend(res, {a:l1[v:val]: a:l2[v:val]})')
  return res
endfunction
Luc Hermitte
  • 31,979
  • 7
  • 69
  • 83
  • 1
    Thanks. Perfect solution. So at least now we have got a zip() function for viml. – dNitro May 25 '16 at 16:43
  • 1
    I have just pushed it in my [library plugin](https://github.com/LucHermitte/lh-vim-lib) along with a `lh#list#zip()` function. – Luc Hermitte May 25 '16 at 16:58