Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Making my dictionary comprehension more efficient

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading