244 python dictionary
如何在Python中打印深度为~4的字典呢?我尝试使用漂亮的打印pprint(),但它不起作用:
import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(mydict)
Run Code Online (Sandbox Code Playgroud)
我只想"\t"为每个嵌套设置一个缩进(),这样我得到这样的东西:
key1
value1
value2
key2
value1
value2
Run Code Online (Sandbox Code Playgroud)
等等
我怎样才能做到这一点?
Ken*_*Ken 444
我的第一个想法是JSON序列化程序可能非常擅长嵌套字典,所以我作弊并使用它:
>>> import json
>>> print json.dumps({'a':2, 'b':{'x':3, 'y':{'t1': 4, 't2':5}}},
... sort_keys=True, indent=4)
{
"a": 2,
"b": {
"x": 3,
"y": {
"t1": 4,
"t2": 5
}
}
}
Run Code Online (Sandbox Code Playgroud)
sth*_*sth 124
我不确定你想要格式化的样子,但你可以从这样的函数开始:
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))
Run Code Online (Sandbox Code Playgroud)
(对于python 2用户:从__future__导入打印功能)
And*_*nko 46
你可以通过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
Run Code Online (Sandbox Code Playgroud)
y.p*_*ann 34
至于做了什么,我没有看到任何漂亮的打印机,至少模仿python解释器的输出与非常简单的格式,所以这是我的:
class Formatter(object):
def __init__(self):
self.types = {}
self.htchar = '\t'
self.lfchar = '\n'
self.indent = 0
self.set_formater(object, self.__class__.format_object)
self.set_formater(dict, self.__class__.format_dict)
self.set_formater(list, self.__class__.format_list)
self.set_formater(tuple, self.__class__.format_tuple)
def set_formater(self, obj, callback):
self.types[obj] = callback
def __call__(self, value, **args):
for key in args:
setattr(self, key, args[key])
formater = self.types[type(value) if type(value) in self.types else object]
return formater(self, value, self.indent)
def format_object(self, value, indent):
return repr(value)
def format_dict(self, value, indent):
items = [
self.lfchar + self.htchar * (indent + 1) + repr(key) + ': ' +
(self.types[type(value[key]) if type(value[key]) in self.types else object])(self, value[key], indent + 1)
for key in value
]
return '{%s}' % (','.join(items) + self.lfchar + self.htchar * indent)
def format_list(self, value, indent):
items = [
self.lfchar + self.htchar * (indent + 1) + (self.types[type(item) if type(item) in self.types else object])(self, item, indent + 1)
for item in value
]
return '[%s]' % (','.join(items) + self.lfchar + self.htchar * indent)
def format_tuple(self, value, indent):
items = [
self.lfchar + self.htchar * (indent + 1) + (self.types[type(item) if type(item) in self.types else object])(self, item, indent + 1)
for item in value
]
return '(%s)' % (','.join(items) + self.lfchar + self.htchar * indent)
Run Code Online (Sandbox Code Playgroud)
要初始化它:
pretty = Formatter()
Run Code Online (Sandbox Code Playgroud)
它可以支持为已定义类型添加格式化程序,您只需要为此创建一个函数,并使用set_formater将其绑定到所需的类型:
from collections import OrderedDict
def format_ordereddict(self, value, indent):
items = [
self.lfchar + self.htchar * (indent + 1) +
"(" + repr(key) + ', ' + (self.types[
type(value[key]) if type(value[key]) in self.types else object
])(self, value[key], indent + 1) + ")"
for key in value
]
return 'OrderedDict([%s])' % (','.join(items) +
self.lfchar + self.htchar * indent)
pretty.set_formater(OrderedDict, format_ordereddict)
Run Code Online (Sandbox Code Playgroud)
由于历史原因,我保留了以前漂亮的打印机,它是一个函数而不是类,但它们都可以使用相同的方式,类版本只允许更多:
def pretty(value, htchar='\t', lfchar='\n', indent=0):
nlch = lfchar + htchar * (indent + 1)
if type(value) is dict:
items = [
nlch + repr(key) + ': ' + pretty(value[key], htchar, lfchar, indent + 1)
for key in value
]
return '{%s}' % (','.join(items) + lfchar + htchar * indent)
elif type(value) is list:
items = [
nlch + pretty(item, htchar, lfchar, indent + 1)
for item in value
]
return '[%s]' % (','.join(items) + lfchar + htchar * indent)
elif type(value) is tuple:
items = [
nlch + pretty(item, htchar, lfchar, indent + 1)
for item in value
]
return '(%s)' % (','.join(items) + lfchar + htchar * indent)
else:
return repr(value)
Run Code Online (Sandbox Code Playgroud)
要使用它:
>>> a = {'list':['a','b',1,2],'dict':{'a':1,2:'b'},'tuple':('a','b',1,2),'function':pretty,'unicode':u'\xa7',("tuple","key"):"valid"}
>>> a
{'function': <function pretty at 0x7fdf555809b0>, 'tuple': ('a', 'b', 1, 2), 'list': ['a', 'b', 1, 2], 'dict': {'a': 1, 2: 'b'}, 'unicode': u'\xa7', ('tuple', 'key'): 'valid'}
>>> print(pretty(a))
{
'function': <function pretty at 0x7fdf555809b0>,
'tuple': (
'a',
'b',
1,
2
),
'list': [
'a',
'b',
1,
2
],
'dict': {
'a': 1,
2: 'b'
},
'unicode': u'\xa7',
('tuple', 'key'): 'valid'
}
Run Code Online (Sandbox Code Playgroud)
与其他版本相比:
Jua*_*ali 26
最 Pythonic 的方法之一是使用已经构建的pprint模块。
定义打印深度所需的参数正如您所料 depth
import pprint
pp = pprint.PrettyPrinter(depth=4)
pp.pprint(mydict)
Run Code Online (Sandbox Code Playgroud)
就是这样 !
Nic*_*mer 24
这里的现代解决方案是使用rich。安装与
pip install rich
Run Code Online (Sandbox Code Playgroud)
并用作
pip install rich
Run Code Online (Sandbox Code Playgroud)
输出的缩进很好:
yas*_*ini 14
by this way you can print it in pretty way forexample your dictionary name is yasin
import json
print (json.dumps(yasin, indent=2))
Run Code Online (Sandbox Code Playgroud)
gsa*_*ras 10
我也必须传递default参数,如下所示:
print(json.dumps(my_dictionary, indent=4, default=str))
Run Code Online (Sandbox Code Playgroud)
如果您希望对键进行排序,则可以执行以下操作:
print(json.dumps(my_dictionary, sort_keys=True, indent=4, default=str))
Run Code Online (Sandbox Code Playgroud)
为了修复此类型错误:
TypeError: Object of type 'datetime' is not JSON serializable
Run Code Online (Sandbox Code Playgroud)
这是由于日期时间是字典中的一些值造成的。
另一种选择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)
Run Code Online (Sandbox Code Playgroud)
输出:
{
'1': '1',
'2': '2',
'3': [1, 2, 3, 4, 5],
'4': {
'1': '1',
'2': '2',
'3': [1, 2, 3, 4, 5]
}
}
Run Code Online (Sandbox Code Playgroud)
免责声明:我是该包的作者。
有关与其他格式化程序的比较,请参阅其他格式化程序。
与 不同的是pprint.pprint,prettyformatter垂直分布更多并尝试更多地对齐项目。
与json.dumps,prettyformatter通常更紧凑,并尝试在合理的情况下对齐字典值。
from prettyformatter import pprint
batters = [
{"id": "1001", "type": "Regular"},
{"id": "1002", "type": "Chocolate"},
{"id": "1003", "type": "Blueberry"},
{"id": "1004", "type": "Devil's Food"},
]
toppings = [
{"id": "5001", "type": None},
{"id": "5002", "type": "Glazed"},
{"id": "5005", "type": "Sugar"},
{"id": "5007", "type": "Powdered Sugar"},
{"id": "5006", "type": "Chocolate with Sprinkles"},
{"id": "5003", "type": "Chocolate"},
{"id": "5004", "type": "Maple"},
]
data = {"id": "0001", "type": "donut", "name": "Cake", "ppu": 0.55, "batters": batters, "topping": toppings}
pprint(data)
Run Code Online (Sandbox Code Playgroud)
输出:
{
"id" : "0001",
"type" : "donut",
"name" : "Cake",
"ppu" : 0.55,
"batters":
[
{"id": "1001", "type": "Regular"},
{"id": "1002", "type": "Chocolate"},
{"id": "1003", "type": "Blueberry"},
{"id": "1004", "type": "Devil's Food"},
],
"topping":
[
{"id": "5001", "type": None},
{"id": "5002", "type": "Glazed"},
{"id": "5005", "type": "Sugar"},
{"id": "5007", "type": "Powdered Sugar"},
{"id": "5006", "type": "Chocolate with Sprinkles"},
{"id": "5003", "type": "Chocolate"},
{"id": "5004", "type": "Maple"},
],
}
Run Code Online (Sandbox Code Playgroud)
请参阅此处获取完整文档。
与 不同的是pprint.pprint,prettyformatter支持通过参数进行 JSON 转换json=True。这包括更改Noneto null、Trueto true、Falsetofalse以及正确使用引号。
与 不同的是json.dumps,prettyformatter支持更多数据类型的 JSON 强制转换。这包括将 any dataclassor更改mapping为 adict以及将 anyiterable更改为 a list。
from dataclasses import dataclass
from prettyformatter import PrettyDataclass, pprint
@dataclass(unsafe_hash=True)
class Point(PrettyDataclass):
x: int
y: int
pprint((Point(1, 2), Point(3, 4)), json=True)
Run Code Online (Sandbox Code Playgroud)
输出:
[{"x": 1, "y": 2}, {"x": 3, "y": 4}]
Run Code Online (Sandbox Code Playgroud)
pprint.pprint与或不同json.dumps,prettyformatter支持使用其他类型轻松定制。
为子类实现__pargs__和/或__pkwargs__方法prettyformatter.PrettyClass允许人们轻松地以"cls_name(*args, **kwargs)".
from prettyformatter import PrettyClass
class Dog(PrettyClass):
def __init__(self, name, **kwargs):
self.name = name
def __pkwargs__(self):
return {"name": self.name}
print(Dog("Fido"))
"""
Dog(name="Fido")
"""
print(Dog("Fido"), json=True)
"""
{"name": "Fido"}
"""
Run Code Online (Sandbox Code Playgroud)
实现该__pformat__方法允许更具体地实现该pformat功能。
实现该@prettyformatter.register函数还允许以与实现相同的方式自定义已经存在的类__pformat__。
import numpy as np
from prettyformatter import pprint, register
@register(np.ndarray)
def pformat_ndarray(obj, specifier, depth, indent, shorten, json):
if json:
return pformat(obj.tolist(), specifier, depth, indent, shorten, json)
with np.printoptions(formatter=dict(all=lambda x: format(x, specifier))):
return repr(obj).replace("\n", "\n" + " " * depth)
pprint(dict.fromkeys("ABC", np.arange(9).reshape(3, 3)))
Run Code Online (Sandbox Code Playgroud)
输出:
{
"A":
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]]),
"B":
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]]),
"C":
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]]),
}
Run Code Online (Sandbox Code Playgroud)
正如其他人发布的那样,您可以使用 recursion/dfs 打印嵌套的字典数据,如果是字典则递归调用;否则打印数据。
def print_json(data):
if type(data) == dict:
for k, v in data.items():
print k
print_json(v)
else:
print data
Run Code Online (Sandbox Code Playgroud)
pout可以很好地打印你扔给它的任何东西,例如(data从另一个答案借用):
data = {'a':2, 'b':{'x':3, 'y':{'t1': 4, 't2':5}}}
pout.vs(data)
Run Code Online (Sandbox Code Playgroud)
将导致输出打印到屏幕上,如:
{
'a': 2,
'b':
{
'y':
{
't2': 5,
't1': 4
},
'x': 3
}
}
Run Code Online (Sandbox Code Playgroud)
或者您可以返回对象的格式化字符串输出:
v = pout.s(data)
Run Code Online (Sandbox Code Playgroud)
它的主要用例是用于调试,因此它不会被对象实例或任何东西阻塞,并且它可以按照您的预期处理 unicode 输出,适用于 python 2.7 和 3。
披露:我是 pout 的作者和维护者。
您可以使用 print-dict
from print_dict import pd
dict1 = {
'key': 'value'
}
pd(dict1)
Run Code Online (Sandbox Code Playgroud)
输出:
{
'key': 'value'
}
Run Code Online (Sandbox Code Playgroud)
此Python 代码的输出:
{
'one': 'value-one',
'two': 'value-two',
'three': 'value-three',
'four': {
'1': '1',
'2': '2',
'3': [1, 2, 3, 4, 5],
'4': {
'method': <function custom_method at 0x7ff6ecd03e18>,
'tuple': (1, 2),
'unicode': '?',
'ten': 'value-ten',
'eleven': 'value-eleven',
'3': [1, 2, 3, 4]
}
},
'object1': <__main__.Object1 object at 0x7ff6ecc588d0>,
'object2': <Object2 info>,
'class': <class '__main__.Object1'>
}
Run Code Online (Sandbox Code Playgroud)
安装:
$ pip install print-dict
Run Code Online (Sandbox Code Playgroud)
披露:我是作者print-dict
| 归档时间: |
|
| 查看次数: |
200176 次 |
| 最近记录: |