【问题标题】:How to change the key color when printing a python dictionary打印python字典时如何更改键颜色
【发布时间】:2020-02-02 22:29:29
【问题描述】:

是否有内置的 python 函数允许我更改字典中的键颜色,以便更有效地将它们与对应的值区分开来?

我目前正在使用 jupyter 笔记本并打印出字典,并希望它显示类似于以下输出的内容:

in:
data


上面的数据是一个python字典。

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

这样键是蓝色的,值是不同的颜色。我想这样做的原因是因为我正在打印一个密钥长度变化很大的字典,因此更难阅读。

【问题讨论】:

    标签: python python-3.x jupyter-notebook jupyter


    【解决方案1】:

    如果您的意思是希望颜色显示在 print 语句的输出中,那么这可以解决问题。

    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)
    

    【讨论】:

      【解决方案2】:

      此答案基于@bashBedlam 提供的答案。

      下面的函数接受您要打印的字典,以及所需格式的键值对的格式。

      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])
      

      【讨论】:

        猜你喜欢
        • 2021-07-14
        • 1970-01-01
        • 2017-07-14
        • 1970-01-01
        • 2013-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多