简体   繁体   English

打印python字典时如何更改键颜色

[英]How to change the key color when printing a python dictionary

Is there a built in python function that allows me to change the key colors in a dictionary so that I can more effectively distinguish them from their corresponding values?是否有内置的 python 函数允许我更改字典中的键颜色,以便我可以更有效地将它们与其对应的值区分开来?

I am currently using a jupyter notebook and printing out a dictionary and would like it to show something similar to the output below:我目前正在使用 jupyter notebook 并打印字典,并希望它显示类似于以下输出的内容:

in:
data


Data above is a python dictionary.上面的数据是一个python字典。

out: 
{
 key1:value1
 key2:value2
 ...
 keyn:valuen
}

Such that the keys are in blue and the values are in a different color.这样键是蓝色的,值是不同的颜色。 The reason I want to do this is because I am printing a dictionary that varies a lot in key length, therefore making it much harder to read.我想这样做的原因是因为我正在打印一本密钥长度变化很大的字典,因此更难阅读。

If you mean that you want the colors to show in the output of a print statement then this will do the trick.如果您的意思是希望颜色显示在打印语句的输出中,那么这将起作用。

red = "\033[1;31m"
blue = "\033[1;34m"
green = "\033[1;32m"
no_color = "\033[0m"

out = {
    'key1' : 'value1',
    'key2' : 'value2',
    'key3' : 'value3' }

for key in out.keys () :
    print (red, key, blue, out [key])
print (no_color)

This answer builds upon the answer provided by @bashBedlam .这个答案建立在@bashBedlam 提供的答案之上。

The function below accepts the dictionary that you would like to print, and the formats for the key value pairs in the desired formats.下面的函数接受您要打印的字典以及所需格式的键值对格式。

def dprint(d,key_format = "\033[1;32m",value_format = "\033[1;34m"):
    for key in d.keys() :
        print (key_format, key, value_format, d[key])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM