Search code examples
pythonpython-3.xdictionarycolorsansi-escape

How do I print the value of a dictionary in color with Python?


I know how I can print the statements in color: print("\033[32m Hello! \033[0m") or with Rich print("[green]Hello![/green]").

But how do I print a dictionary's value(s) in color when it comes from a list? Or a dictionary's value(s) in general?

EX:

dict = {
        "greetings" : ["hello", "bonjour"],
        "goodbyes" : ["adios", "4"]
    }
newList = ["hola", "barev"]
dict.update({"greetings" : newList})
print(dict["greetings"][0])
print(dict)

The two above print statements would print in black, how would I make it print in green? What would I need to do? What packages/libraries would I need to download if needed?


Solution

  • Be aware that there are Python reserved words like dict and sum that should be avoided as variables. You could try to print with f-strings:

    dic = {
            "greetings": ["hello", "bonjour"],
            "goodbyes": ["adios", "4"]
        }
    newList = ["hola", "barev"]
    dic.update({"greetings": newList})
    
    hola = dic["greetings"][0]
    print(f"\033[32m{hola}\033[0m")
    
    print(f"\033[32m{dic}\033[0m")
    

    Or this:

    print("\033[32m{}\033[0m".format(hola))
    
    print("\033[32m{}\033[0m".format(dic))