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