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

Question:

I know how I can print the statements in color: print("33[32m Hello! 33[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?

Asked By: edwardvth

||

Answers:

from termcolor import colored

print(colored(dict, 'green'))
Answered By: Michael Hodel

Use

$ pip install pygments

From the FAQ:

pygmentize -f html /path/to/file.py

will get you a long way toward rendering
those print’ed or pretty pp‘ed data structures
in glorious technicolor.

Answered By: J_H

With rich, you can do

d = {
        "greetings" : ["hello", "bonjour"],
        "goodbyes" : ["adios", "4"]
}
console.print(d, style="green", highlight=False)
console.print(d["greetings"][0], style="green", highlight=False)

Answered By: Yash Rathi

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"33[32m{hola}33[0m")

print(f"33[32m{dic}33[0m")

Or this:

print("33[32m{}33[0m".format(hola))

print("33[32m{}33[0m".format(dic))
Answered By: perpetualstudent

check out the package rich that does a fantastic job of "pretty printing" objects in color…

You can pip install it, and then just override the default print command:

from rich import print

a = {1: 'dog', 2: 'cat', 3:'bird'}
b = ['horse', 'goat', 'cheetah']

print(a)
print(b)

enter image description here

Answered By: AirSquid