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

I have a question regarding overwriting multiple variables in python

In a program, I’m writing for a school project where you basically pick your subjects and the colours that you want each of those subjects to be. I have multiple variables which represent colours, but I want to overwrite them with hex values I’ve set. How would I do this without writing a hundred "if statements".

For reference here is the code I’ve currently got and trying to find a solution for:

LangColour = parser.get('Colour', 'lang')
HmtColour = parser.get('Colour', 'hmt')
SciColour = parser.get('Colour', 'sci')
ArtColour = parser.get('Colour', 'art')
MathColour = parser.get('Colour', 'math')
EngColour = parser.get('Colour', 'eng')

Red = '#ff6666'
Orange = '#ff9966'
Yellow = '#ffff66'
Green = '#99ff99'
DarkBlue = '#99ccff'
LightBlue = '#99ffff'
Pink = '#ff99ff'
Purple = '#cc99ff'
Grey = '#bcbcbc'

And the values for parser.get are being pulled from a .ini file:

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

[Colour]
lang = Dark Blue
hmt = Orange
sci = Pink
art = Green
math = Light Blue
eng = Red

I have no idea what to do, I’m relatively inexperienced so I’m really not sure what I can try. I’ve tried searching it up, and the main results were to write "if statements" which is what I’d like to avoid as I feel there’s probably a better way to do it.

>Solution :

You can use a dictionary to map the string values from the .ini file to the corresponding hex values.

Create a dictionary with the keys being the string values from the .ini file and the values being the corresponding hex values. Then, you can use the dictionary to assign the hex values to the variables.

For example:

 hex_colors = {
'Dark Blue': '#99ccff',
'Orange': '#ff9966',
'Pink': '#ff99ff',
'Green': '#99ff99',
'Light Blue': '#99ffff',
'Red': '#ff6666'
    }

LangColour = hex_colors[parser.get('Colour', 'lang')]
HmtColour = hex_colors[parser.get('Colour', 'hmt')]
SciColour = hex_colors[parser.get('Colour', 'sci')]
ArtColour = hex_colors[parser.get('Colour', 'art')]
MathColour = hex_colors[parser.get('Colour', 'math')]
EngColour = hex_colors[parser.get('Colour', 'eng')]

This way you don’t need to write 100 if statements and it’s more readable and easy to maintain.

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