Saturday, February 8, 2014

VimL List Gymnastics


Some common flexing between lists and dicts in VimL.

let a_list = range(1,10)
echo a_list
"=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

" from list -> dict
let a_dict = {}
call map(copy(a_list), 'extend(a_dict, {v:val : (v:val * v:val)})')
echo a_dict
"=> {'1': 1, '2': 4, '3': 9, '4': 16, '5': 25, '6': 36, '7': 49, '8': 64, '9': 81, '10': 100}

" from dict -> list
echo keys(a_dict)
"=> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

echo map(keys(a_dict), 'str2nr(v:val)')
"=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

echo values(a_dict)
"=> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

" collecting a single dictionary from multiple dictionaries
let b_text = "one thing\ntwo things\nthree more things"
let b_dict = {}
call map(split(b_text, '\n'), 'extend(b_dict, {split(v:val)[0] : v:val})')
echo b_dict
"=> {'one': 'one thing', 'two': 'two things', 'three': 'three more things'}

No comments:

Post a Comment