Reputation: 37
I am using python 3 to PUT some data via API on a website. I need to upload the data with following format:
data = {'MA:C0:AD:DR:ES:S1': {'ip': '1.1.1.1', 'name': 'TEST2'}, 'MA:C0:AD:DR:ES:S2': {'ip': '2.2.2.2', 'name': 'TEST'}}
I have a CSV file where I have all the mac addresses, IPs and names I want to upload. The CSV looks like this:
MAC, IP, NAME
MA:C0:AD:DR:ES:S1, 1.1.1.1, TEST
MA:C0:AD:DR:ES:S2, 2.2.2.2, TEST2
MA:C0:AD:DR:ES:S3, 3.3.3.3, TEST3
MA:C0:AD:DR:ES:S4, 4.4.4.4, TEST4
How can I use this data from the CSV to upload them like a dictionary(see sample) to the website? Thanks in advance!
Upvotes: 0
Views: 67
Reputation: 23825
Like this
import csv
data = {}
with open("input.csv") as tsvfile:
reader = csv.reader(tsvfile, delimiter=",")
for idx,row in enumerate(reader):
if idx > 0:
data[row[0]] = {'ip': row[1],'name':row[2]}
print(data)
input.csv
MAC, IP, NAME
MA:C0:AD:DR:ES:S1, 1.1.1.1, TEST
MA:C0:AD:DR:ES:S2, 2.2.2.2, TEST2
MA:C0:AD:DR:ES:S3, 3.3.3.3, TEST3
MA:C0:AD:DR:ES:S4, 4.4.4.4, TEST4
output
{'MA:C0:AD:DR:ES:S1': {'ip': ' 1.1.1.1', 'name': ' TEST'}, 'MA:C0:AD:DR:ES:S2': {'ip': ' 2.2.2.2', 'name': ' TEST2'}, 'MA:C0:AD:DR:ES:S3': {'ip': ' 3.3.3.3', 'name': ' TEST3'}, 'MA:C0:AD:DR:ES:S4': {'ip': ' 4.4.4.4', 'name': ' TEST4'}}
Upvotes: 1