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

Python : * Operator in list comprehension

Evening all,
I have recently discover the * operator to unpack my list. I find it quite elegant but I am a bit struggling with it.

Please find below an example :

from matplotlib.pyplot import Line2D
COLOR_FCT = {
"a": ["blue", "Al", "-"],
"b": ["orange", "Bv", "-"],
"c": ["green", "Cx", "-"],
"d": ["k", "Ds", "--"],
}

legend = [
Line2D(
[0],[0],color=COLOR_FCT[item][0],lw=2,ls=COLOR_FCT[item][2],label=COLOR_FCT[item][1],)
for item in ["a", "b", "c"]]

Is there a way to avoid assigning myself the color, ls and label variables using the * operator ?
I made a test with :
for zip(*list(item))
but I would be grateful for insights or additional documentation.
Thanks a lot,
Mat

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

>Solution :

If you changed the dictionary of lists to a dictionary of dictionaries, you can use the similar ** unpacking operator:

COLOR_FCT = {
    "a": {"color": "blue", "label": "Al", "ls": "-"],
    "b": ["color": "orange", "label": "Bv", "ls": "-"],
]

legend = [
    Line2D([0],[0], **COLOR_FCT[item])
    for item in ["a", "b", "c"]
]

This unpacks the dictionaries into the argument list.

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