【发布时间】:2017-12-15 23:13:38
【问题描述】:
我有一个 python 字典对象,我需要将数据写入 CSV 文件。我是 python 编程的新手。所以我想知道是否有人可以指导我。
这是我的对象。
dict = [{u'interface': [{u'interface-down-reason': u'LACP Convergence Timeout',
u'interface-name': u'ethernet28:1',
u'leaf-group': u'R2',
u'member-type': u'',
u'mode': u'lacp',
u'op-state': u'down',
u'phy-state': u'up',
u'switch-name': u'R2L2'},
{u'interface-down-reason': u'LACP Protocol Initiated',
u'interface-name': u'ethernet28:1',
u'leaf-group': u'R2',
u'member-type': u'',
u'mode': u'lacp',
u'op-state': u'down',
u'phy-state': u'up',
u'switch-name': u'R2L1'}],
u'name': u'LACP-Test'},
{u'interface': [{u'interface-down-reason': u'None',
u'interface-name': u'ethernet54:4',
u'leaf-group': u'R1',
u'member-type': u'',
u'mode': u'static-auto-vswitch-inband',
u'op-state': u'up',
u'phy-state': u'up',
u'switch-name': u'R1L1'},
{u'interface-down-reason': u'None',
u'interface-name': u'ethernet54:4',
u'leaf-group': u'R1',
u'member-type': u'',
u'mode': u'static-auto-vswitch-inband',
u'op-state': u'up',
u'phy-state': u'up',
u'switch-name': u'R1L2'}],
u'name': u'LAX-K8-MASTER-NODE'}]
如您所见,它由多个键值对组成,并且一些键具有字典列表。
我一直在阅读 csv.Dictwiter,我想包含如下所示的字段名称
export_fields = ['name','interface-name', 'op-state', 'phy-state']
然而,挑战在于某些字段名称在键“接口”的字典中。
那么我该如何隔离它,以便将其写入 CSV 文件。
如果有人可以分享逻辑或指导我完成,我可以从那里得到它。
感谢您的回复。
【问题讨论】:
-
为了使用
csv.DictWriter,您需要将现有数据转换为没有任何嵌套的简单字典列表。