如何以表格格式格式化Python Ordered-Dictionary

时间:2019-05-08 01:14:38

标签: python-3.x dictionary tabular ordereddictionary

我正在尝试以表格形式格式化Python有序字典,如下所示,我如何以以下格式格式化有序字典数据?

OrderedDict([('parent_ mods', OrderedDict([('pk_release', None), ('product_value', None), ('bar_activity', 'create'), ('host_model', False), ('active', True), ('model_facet', False), ('is_active', True)])),('product_name', OrderedDict([('pk_release', None), ('product_value', None), ('bar_activity', 'create'), ('host_model', False), ('active', True), ('model_facet', False), ('is_active', True)]))])

正在尝试下面的代码来分离Keys和Data-value,但是o / p中仅显示2个dict键。

Import json
dblock=json.loads(relc_json,object_pairs_hook=OrderedDict)
bkeys=list(dblock.keys())
print(bkeys)

输出-

['parent_mods', 'product_name']

我如何将有序字典数据格式化为以下格式?

期望的表格格式-

| parent_mods |

| pk_release | product_value | bar_activity | host_model | active | model_facet | is_active | | None | None | create | False | True | Fasle | True |

|产品名称|

| pk_release | product_value | bar_activity | host_model | active | model_facet | is_active | | None | None | create | False | True | Fasle | True |

1 个答案:

答案 0 :(得分:0)

首先,根字典中只有两个键,因此我不确定您希望输出什么。

对于此输出,可能我在某个地方存储库,但是在格式化方面似乎并不难。

import json

dblock = json.loads(relc_json,
                    object_pairs_hook=OrderedDict)

for key, value in dblock.items():
    print(f'|{key}|')
    print()
    joined_subkeys = '|'.join(value.keys())
    joined_subvalues = '|'.join(value.values())
    print(f'|{joined_subkeys}|')
    print(f'|{joined_subvalues}|')
    print()