I want to add green color to an integer value which is <= 5 and red color to an integer value >5 , inside a dictionary in python.
from colorama import Fore, Back, Style
input_dict = {'key1': 217, 'key2': 2, 'key3': 9, 'key4': 4, 'key5':6}
for key in input_dict:
if input_dict[key] < 5:
<# print input_dict with integer values in red color #>
if output[key]>5:
<# print input_dict with integer values in red color #>
expected output = {'key1': 217 (217 value printed in red color), 'key2': 2 (2 value printed in green color), 'key3': 9 (9 value printed in red color), 'key4': 4 (4 value printed in green color), 'key5': 6 (6 value printed in red color)}
expected output_dictionary = {'key1': 217 (value printed in red color), 'key2': 2 (value printed in green color), 'key3': 9 (value printed in red), 'key4': 4 (value printed in green color), 'key5': 6 (value printed in red color)}
I request your help sincere help here.
The colorama PyPI page is pretty clear on how to access the ANSI escape sequences that need to be printed to change the color of printed text. However, it is quite important to note that:
Even if you do store ANSI colored strings in your dictionary, you probably won't see the colors if you print the whole thing, since printing a dictionary prints the repr of its contents. The repr of a string will escape non-printable characters, like the Escape character that leads off each ANSI sequence. - Blckknght
So, even if you stored the values like
# !pip install colorama
# from colorama import Fore, Back, Style
input_dict = {'key1': 217, 'key2': 2, 'key3': 9, 'key4': 4, 'key5':6}
colored_dict = {k: f'{Fore.RED if v>5 else Fore.GREEN}{v}' for k, v in input_dict.items()}
colored_dict
would just look like
{'key1': '\x1b[31m217', 'key2': '\x1b[32m2', 'key3': '\x1b[31m9', 'key4': '\x1b[32m4', 'key5': '\x1b[31m6'}
Although, if you printed those saved values separately(view examples), the colors will show (just remember to reset so that the color doesn't run on to the next print).
If you just wanted to fill in your code snippet, then: (view output)
for key in input_dict:
if input_dict[key] > 5:
print(repr(key)+':', Fore.RED, input_dict[key], Fore.RESET)
# print input_dict with integer values in red color #
else:
print(repr(key)+':', Fore.GREEN, input_dict[key], Fore.RESET)
# print input_dict with integer values in green color #
If you want it to be printed looking like a dictionary, then:
## setup
thresh, cHi, cLo = 5, Fore.RED, Fore.GREEN
cKey, cNorm = Fore.BLUE, Fore.RESET ## set Fore.RESET for cKey as well to NOT color keys
input_dict = {'key1': 217, 'key2': 2, 'key3': 9, 'key4': 4, 'key5': 6}
def colorFunc(kx, vx):
return cKey+repr(kx)+': '+(cHi if vx>thresh else cLo)+repr(vx)+cNorm
# one line:
print('{', ', '.join(colorFunc(k,v) for k,v in input_dict.items()), '}', sep='')
# multi-line:
print('{\n ', ',\n '.join(colorFunc(k,v) for k,v in input_dict.items()), '\n}', sep='')