1

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?

edwardvth
  • 41
  • 3

5 Answers5

1
from termcolor import colored

print(colored(dict, 'green'))
Michael Hodel
  • 2,845
  • 1
  • 5
  • 10
1

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))
Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
blackraven
  • 5,284
  • 7
  • 19
  • 45
0

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.

J_H
  • 17,926
  • 4
  • 24
  • 44
0

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)

Yash Rathi
  • 551
  • 7
  • 9
0

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

AirSquid
  • 10,214
  • 2
  • 7
  • 31