Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create dictionary from CSV without repeating top level

Tags:

python

I am trying to make an API using a script. It runs but I need to make it iterate the CSV file without appending port_config to each line:

Reading this CSV File:

device_id,port,description
4444,eth1/1,test1
1111,eth1/2,test2
2222,eth1/3,test3
1234,eth1/4,test4

The code I have so far:

for device_id,port,description in devices:
    print(device_id,port,description)
    payload="{\n \"port_config\": { \"%s\": { \"description\": \"%s\"                      
             }\n}\n}" % (port,description)
    print(payload)

Result of above:

{
 "port_config": { "interfacex/x": { "description": "test1" }
}
}
{
 "port_config": { "interfacex/x": { "description": "test2" }
}
}
{
 "port_config": { "interfacex/x": { "description": "test3" }
}
}
{
 "port_config": { "interfacex/x": { "description": "test4" }
}
}

Desired results:

{
    "port_config": {
        "eth1/1": {"description": "test0,"},
        "eth1/2": {"description": "test1,"},
        "eth1/3": {"description": "test2,"},
        "eth1/4": {"description": "test3,"}
    }
}
like image 338
Ali Avatar asked Apr 06 '26 23:04

Ali


1 Answers

Your question still has one problem. The CSV example doesn't exactly match the desired output. Let's say you have the following CSV string.

devices = """device_id,port,description
4444,eth1/1,test1
1111,eth1/2,test2
2222,eth1/3,test3
1234,eth1/4,test4
"""

And you want the following output:

d = {
    "port_config": {
        "eth1/1": {"description": "test1,"},
        "eth1/2": {"description": "test2,"},
        "eth1/3": {"description": "test3,"},
        "eth1/4": {"description": "test4,"},
    }
}

You can easily achieve this in Python by doing some dictionary gymnastics like the following:

import csv
from pprint import pprint

# Input csv.
devices = """device_id,port,description
4444,eth1/1,test1
1111,eth1/2,test2
2222,eth1/3,test3
1234,eth1/4,test4
"""

# Read the data using Python's built-in csv module.
lines = devices.splitlines()
reader = csv.reader(lines)
devices = list(reader)

# Let's initialize the target payloads data structure.
payload = {
    "port_config": {},
}

for idx, (device_id, port, description) in enumerate(devices):
    if idx == 0:
        continue # This line skips the header.
    payload["port_config"][port] = {"description": description}

pprint(payload)

This should give you the following output:

{'port_config': {'eth1/1': {'description': 'test1'},
                 'eth1/2': {'description': 'test2'},
                 'eth1/3': {'description': 'test3'},
                 'eth1/4': {'description': 'test4'}}}
like image 55
Redowan Delowar Avatar answered Apr 10 '26 15:04

Redowan Delowar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!