如何在Python中漂亮地打印深度为~4的字典?我尝试用pprint()进行漂亮的打印,但它不起作用:
import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(mydict)
我只是想要一个缩进(“\t”)为每个嵌套,这样我就会得到这样的东西:
key1
value1
value2
key2
value1
value2
等。
我该怎么做呢?
如何在Python中漂亮地打印深度为~4的字典?我尝试用pprint()进行漂亮的打印,但它不起作用:
import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(mydict)
我只是想要一个缩进(“\t”)为每个嵌套,这样我就会得到这样的东西:
key1
value1
value2
key2
value1
value2
等。
我该怎么做呢?
当前回答
你可以通过PyYAML尝试YAML。它的输出可以微调。我建议从以下开始:
print(yaml.dump(data, allow_unicode=True, default_flow_style=False))
结果非常易读;如果需要,还可以解析回Python。
编辑:
例子:
>>> import yaml
>>> data = {'a':2, 'b':{'x':3, 'y':{'t1': 4, 't2':5}}}
>>> print(yaml.dump(data, default_flow_style=False))
a: 2
b:
x: 3
y:
t1: 4
t2: 5
其他回答
这里有一些东西可以打印任何类型的嵌套字典,同时跟踪“父”字典。
dicList = list()
def prettierPrint(dic, dicList):
count = 0
for key, value in dic.iteritems():
count+=1
if str(value) == 'OrderedDict()':
value = None
if not isinstance(value, dict):
print str(key) + ": " + str(value)
print str(key) + ' was found in the following path:',
print dicList
print '\n'
elif isinstance(value, dict):
dicList.append(key)
prettierPrint(value, dicList)
if dicList:
if count == len(dic):
dicList.pop()
count = 0
prettierPrint(dicExample, dicList)
这是根据不同格式进行打印的一个很好的起点,就像op中指定的那样。你真正需要做的只是围绕打印块进行操作。注意,它将查看该值是否为'OrderedDict()'。这取决于你是否使用容器数据类型集合中的东西,你应该做这些故障保护,这样elif块不会因为它的名字而把它视为一个额外的字典。就像现在,一个例子字典
example_dict = {'key1': 'value1',
'key2': 'value2',
'key3': {'key3a': 'value3a'},
'key4': {'key4a': {'key4aa': 'value4aa',
'key4ab': 'value4ab',
'key4ac': 'value4ac'},
'key4b': 'value4b'}
将打印
key3a: value3a
key3a was found in the following path: ['key3']
key2: value2
key2 was found in the following path: []
key1: value1
key1 was found in the following path: []
key4ab: value4ab
key4ab was found in the following path: ['key4', 'key4a']
key4ac: value4ac
key4ac was found in the following path: ['key4', 'key4a']
key4aa: value4aa
key4aa was found in the following path: ['key4', 'key4a']
key4b: value4b
key4b was found in the following path: ['key4']
~修改代码以适应问题的格式~
lastDict = list()
dicList = list()
def prettierPrint(dic, dicList):
global lastDict
count = 0
for key, value in dic.iteritems():
count+=1
if str(value) == 'OrderedDict()':
value = None
if not isinstance(value, dict):
if lastDict == dicList:
sameParents = True
else:
sameParents = False
if dicList and sameParents is not True:
spacing = ' ' * len(str(dicList))
print dicList
print spacing,
print str(value)
if dicList and sameParents is True:
print spacing,
print str(value)
lastDict = list(dicList)
elif isinstance(value, dict):
dicList.append(key)
prettierPrint(value, dicList)
if dicList:
if count == len(dic):
dicList.pop()
count = 0
使用相同的示例代码,它将打印以下内容:
['key3']
value3a
['key4', 'key4a']
value4ab
value4ac
value4aa
['key4']
value4b
This isn't exactly what is requested in OP. The difference is that a parent^n is still printed, instead of being absent and replaced with white-space. To get to OP's format, you'll need to do something like the following: iteratively compare dicList with the lastDict. You can do this by making a new dictionary and copying dicList's content to it, checking if i in the copied dictionary is the same as i in lastDict, and -- if it is -- writing whitespace to that i position using the string multiplier function.
使用这个函数:
def pretty_dict(d, n=1):
for k in d:
print(" "*n + k)
try:
pretty_dict(d[k], n=n+4)
except TypeError:
continue
这样叫它:
pretty_dict(mydict)
我尝试了以下方法,得到了我想要的结果
方法1: 步骤1:在cmd中输入以下命令安装print_dict
pip install print_dict
步骤2:导入print_dict as
from print_dict import pd
步骤3:使用pd打印
pd(your_dictionary_name)
示例输出:
{
'Name': 'Arham Rumi',
'Age': 21,
'Movies': ['adas', 'adfas', 'fgfg', 'gfgf', 'vbxbv'],
'Songs': ['sdfsd', 'dfdgfddf', 'dsdfd', 'sddfsd', 'sdfdsdf']
}
方法2: 我们也可以使用for循环来使用items方法打印字典
for key, Value in your_dictionary_name.items():
print(f"{key} : {Value}")
yapf的另一个选择:
from pprint import pformat
from yapf.yapflib.yapf_api import FormatCode
dict_example = {'1': '1', '2': '2', '3': [1, 2, 3, 4, 5], '4': {'1': '1', '2': '2', '3': [1, 2, 3, 4, 5]}}
dict_string = pformat(dict_example)
formatted_code, _ = FormatCode(dict_string)
print(formatted_code)
输出:
{
'1': '1',
'2': '2',
'3': [1, 2, 3, 4, 5],
'4': {
'1': '1',
'2': '2',
'3': [1, 2, 3, 4, 5]
}
}
通过这种方式,你可以打印在漂亮的方式,例如你的字典名字是yasin
import json
print (json.dumps(yasin, indent=2))
或者,更安全:
print (json.dumps(yasin, indent=2, default=str))