1
我想从我的csv文件构建一个分层字典(请参阅下面我期待的输出)。如何从csv创建分层字典?
以下是我的代码到目前为止,我正在通过itertools
进行搜索,可能我认为这是我完成此任务所需的最佳工具。我不能使用pandas
。我想我需要将密钥的值放入新的字典中,然后尝试映射策略接口并构建一个新的dict
?
import csv
import pprint
from itertools import groupby
new_dict=[]
with open("test_.csv", "rb") as file_data:
reader = csv.DictReader(file_data)
for keys, grouping in groupby(reader, lambda x: x['groupA_policy']):
new_dict.append(list(grouping))
pprint.pprint(new_dict)
我的CSV文件看起来像这样:
GroupA_Host,groupA_policy,groupA_policy_interface,GroupB_Host,GroupB_policy,GroupB_policy_interface
host1,policy10,eth0,host_R,policy90,eth9
host1,policy10,eth0.1,host_R,policy90,eth9.1
host2,policy20,eth2,host_Q,policy80,eth8
host2,policy20,eth2.1,host_Q,policy80,eth8.1
所需的输出我想要实现的是:
[{'GroupA_Host': 'host1',
'GroupB_Host': 'host_R',
'GroupB_policy': 'policy90',
'groupA_policy': 'policy10',
'interfaces': [{'GroupB_policy_interface': 'eth9',
'group_a_policy_interfaces': 'eth0'},
{'GroupB_policy_interface': 'eth9.1',
'group_a_policy_interface': 'eth0.1'}]},
{'GroupA_host': 'host2',
'GroupB_Host': 'host_Q',
'GroupB_policy': 'policy80',
'groupA_policy': 'policy20',
'interfaces': [{'GroupB_policy_interface': 'eth8',
'groupA_policy_interfaces': 'eth2'},
{'groupA_policy_interface': 'eth8.1',
'groupA_policy_interfaces': 'eth2.1'}]}]
不错,有一个问题。我们是否真的需要这样的陈述?试图了解它在这里的使用。 – zig
是的,如果你只是'd [key] = [interface]',你会覆盖列表而不是附加到它 – thomaskeefe