【Python】打印与格式化输出字典数据

tech2022-11-30  109

 

目录

一. 问题

二. 解决

三. 参考


 

一. 问题

在Python 中想打印一下dict 数据,发现如下实际需求:

没有格式化输出dict 映射到 json

 

实际过程中遇到如下问题:

使用pprint 模块,发现无法达到效果使用json 模块,发现字典中Set 数据类型,会导致报错

 

二. 解决

自己写了一个工具类:

# -*- coding:utf-8 -*- # import types import collections import json def dicts(dump_self): ''' the custom dictionary printing and formatting tool ''' result = {} if dump_self is not None: for item in dir(dump_self): # filter inner field by fieldname if item.startswith('_') or item == 'metadata': continue value = getattr(dump_self, item) # filter inner field by value type if callable(value): continue # if type(value) not in (types.NoneType, types.IntType, # types.LongType, types.StringType, # types.UnicodeType, types.DictType): # continue result[item] = getattr(dump_self, item) keys = result.keys() keys.sort() results = collections.OrderedDict() # 有序字典 for key in keys: results[key] = result[key] result.clear() result = results json_list = json.dumps(result, indent=4, cls=SetEncoder) # print(json_list) return json_list return result class SetEncoder(json.JSONEncoder): ''' python set encoder and then refer to\n - https://stackoverflow.com/questions/8230315/how-to-json-serialize-sets - https://docs.python.org/2.7/library/json.html#json.JSONEncoder - https://docs.python.org/3/library/json.html#json.JSONEncoder ''' def default(self, obj): if isinstance(obj, set): return list(obj) return json.JSONEncoder.default(self, obj)

如何使用呢?

参考如下所示:

# -*- coding:utf-8 -*- import dicts dict_origin = {'a': 1, 'b': 'bb'} dict_with_format = dicts(dict_origin) print(dict_with_format)

 

三. 参考

https://docs.python.org/2.7/library/json.htmlhttps://docs.python.org/2.7/library/json.html#encoders-and-decodershttps://docs.python.org/3/library/json.htmlhttps://docs.python.org/3/library/json.html#encoders-and-decoders

 

(完)

 

最新回复(0)