如何在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
等。
我该怎么做呢?
当前回答
This class prints out a complex nested dictionary with sub dictionaries and sub lists.
##
## Recursive class to parse and print complex nested dictionary
##
class NestedDictionary(object):
def __init__(self,value):
self.value=value
def print(self,depth):
spacer="--------------------"
if type(self.value)==type(dict()):
for kk, vv in self.value.items():
if (type(vv)==type(dict())):
print(spacer[:depth],kk)
vvv=(NestedDictionary(vv))
depth=depth+3
vvv.print(depth)
depth=depth-3
else:
if (type(vv)==type(list())):
for i in vv:
vvv=(NestedDictionary(i))
depth=depth+3
vvv.print(depth)
depth=depth-3
else:
print(spacer[:depth],kk,vv)
##
## Instatiate and execute - this prints complex nested dictionaries
## with sub dictionaries and sub lists
## 'something' is a complex nested dictionary
MyNest=NestedDictionary(weather_com_result)
MyNest.print(0)
其他回答
下面是我根据sth的注释写的函数。它的工作原理与json相同。转储与缩进,但我使用制表符而不是缩进的空间。在Python 3.2+中,您可以直接将缩进指定为'\t',但在2.7中不能。
def pretty_dict(d):
def pretty(d, indent):
for i, (key, value) in enumerate(d.iteritems()):
if isinstance(value, dict):
print '{0}"{1}": {{'.format( '\t' * indent, str(key))
pretty(value, indent+1)
if i == len(d)-1:
print '{0}}}'.format( '\t' * indent)
else:
print '{0}}},'.format( '\t' * indent)
else:
if i == len(d)-1:
print '{0}"{1}": "{2}"'.format( '\t' * indent, str(key), value)
else:
print '{0}"{1}": "{2}",'.format( '\t' * indent, str(key), value)
print '{'
pretty(d,indent=1)
print '}'
Ex:
>>> dict_var = {'a':2, 'b':{'x':3, 'y':{'t1': 4, 't2':5}}}
>>> pretty_dict(dict_var)
{
"a": "2",
"b": {
"y": {
"t2": "5",
"t1": "4"
},
"x": "3"
}
}
最python化的方法之一是使用已经构建的pprint模块。
定义打印深度所需的参数与您预期的深度相同
import pprint
pp = pprint.PrettyPrinter(depth=4)
pp.pprint(mydict)
就是这样!
我不确定你到底想要什么样的格式,但你可以从这样一个函数开始:
def pretty(d, indent=0):
for key, value in d.items():
print('\t' * indent + str(key))
if isinstance(value, dict):
pretty(value, indent+1)
else:
print('\t' * (indent+1) + str(value))
我必须传递默认参数,就像这样:
print(json.dumps(my_dictionary, indent=4, default=str))
如果你想要键排序,你可以这样做:
print(json.dumps(my_dictionary, sort_keys=True, indent=4, default=str))
为了修复此类型错误:
TypeError: Object of type 'datetime' is not JSON serializable
这是由于datetimes是字典中的一些值。
某物,我觉得很漂亮
def pretty(d, indent=0):
for key, value in d.iteritems():
if isinstance(value, dict):
print '\t' * indent + (("%30s: {\n") % str(key).upper())
pretty(value, indent+1)
print '\t' * indent + ' ' * 32 + ('} # end of %s #\n' % str(key).upper())
elif isinstance(value, list):
for val in value:
print '\t' * indent + (("%30s: [\n") % str(key).upper())
pretty(val, indent+1)
print '\t' * indent + ' ' * 32 + ('] # end of %s #\n' % str(key).upper())
else:
print '\t' * indent + (("%30s: %s") % (str(key).upper(),str(value)))