I have a list of strings. For example:
lst = ['aa bb cc', 'dd ee ff gg']
Each string in the list is known to contain 2 or more whitespace delimited tokens.
I want to build a dictionary keyed by the last token with the first token as its value.
The following dictionary comprehension achieves this:
d = {e.split()[-1]: e.split()[0] for e in lst}
This gives me:
{'cc': 'aa', 'gg': 'dd'}
…which is exactly what I want.
However, this means that the element e will have its split() function called twice per iteration over lst.
I can’t help thinking that there must be a way to avoid this but I just can’t figure it out.
Any ideas?
>Solution :
Using map:
d = {v[-1]: v[0] for v in map(str.split, lst)}