Skip to content Skip to sidebar Skip to footer

Create A Dict Of List Using Python From Csv

I have a csv file with data as below XPATH,ColumName,CSV_File_Name,ParentKey /integration-outbound:IntegrationEntity/integrationEntityDetails/supplier/forms/form[]/id,id,integratio

Solution 1:

Try this:

from csv import DictReader
from collections import defaultdict

withopen('data.csv') as fp:
    csv_reader = DictReader(fp)
    data = [row['XPATH'].strip('/').replace('/', '.').split('[]') for row in csv_reader]

res = defaultdict(set)
for x in data:
    iflen(x) > 1:
        res[len(x) -1].add(''.join(x[: -1]))
res = {k: list(v) for k, v in res.items()}
print(res)

Output:

{1: ['integration-outbound:IntegrationEntity.integrationEntityHeader.attachments.attachment',
  'integration-outbound:IntegrationEntity.integrationEntityDetails.supplier.forms.form'],
 2: ['integration-outbound:IntegrationEntity.integrationEntityDetails.supplier.forms.form.records.record'],
 3: ['integration-outbound:IntegrationEntity.integrationEntityDetails.supplier.forms.form.records.record.fields.field']}

Post a Comment for "Create A Dict Of List Using Python From Csv"