如何从csv创建分层字典?

时间:2017-08-05 19:57:31

标签: python csv dictionary

我正在尝试从我的csv文件构建一个分层的dict(请参阅下面我想要的输出)。

以下是我的代码到目前为止,我正在搜索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'}]}]

1 个答案:

答案 0 :(得分:0)

我认为这里不需要itertools。重要的是要认识到你正在使用('GroupA_Host', 'GroupB_Host', 'groupA_policy', 'GroupB_policy')作为分组的关键 - 所以你可以使用字典来收集键上这个键的接口:

d = {}

for row in reader:
    key = row['GroupA_Host'], row['GroupB_Host'], row['groupA_policy'], row['GroupB_policy']
    interface = {'groupA_policy_interface': row['groupA_policy_interface'], 
                 'GroupB_policy_interface': row['GroupB_policy_interface']
    }

    if key in d:
        d[key].append(interface)
    else:
        d[key] = [interface]

as_list = []
for key, interfaces in d.iteritems():
    record = {}
    record['GroupA_Host'] = key[0]
    record['GroupB_Host'] = key[1]
    record['groupA_policy'] = key[2]
    record['GroupB_policy'] = key[3]
    record['interfaces'] = interfaces
    as_list.append(record)