SIDP
SIDP

Reputation: 23

Use csv column as function arguments

csv

name;subnet
name_a;192.168.111.0/24
name_b;192.168.168.0/24
name_c;192.168.29.0/24

I try to run a function with a for loop for every column from a csv by passing the column values to function arguments. How should I do this?

I'm not sure if I have to import the csv content to a list, dict or if it is possible to directly use the columns as function arguments.

with open(csv_address_objects, mode='r', encoding='utf-8-sig') as csv_file:
    csv_reader = csv.DictReader(csv_file, delimiter=';')
    list_of_csv = dict(csv_reader)

Upvotes: 2

Views: 712

Answers (3)

Zach Young
Zach Young

Reputation: 11188

You were on the right track with just the code you had.

For the CSV module, reader and DictReader return an iterator over the "rows" of the CSV being read. In the case of DictReader, a row is a dict keyed to your CSV's column names (header), like:

{"name": "name_a", "subnet": "192.168.111.0/24"}

So, to iterate over your rows and use the two column values to pass to your function, you only need to make this small addition:

import csv

def my_func(name, subnet):
    print(f'doing something with name="{name}" and subnet="{subnet}"')

with open("input.csv", mode="r", encoding="utf-8-sig") as csv_file:
    csv_reader = csv.DictReader(csv_file, delimiter=";")

    for row in csv_reader:
        my_func(row["name"], row["subnet"])

        # or pass the dict's key-value pairs with `**` syntax
        # my_func(**row)

When I run that against your sample CSV, I get:

doing something with name="name_a" and subnet="192.168.111.0/24"
doing something with name="name_b" and subnet="192.168.168.0/24"
doing something with name="name_c" and subnet="192.168.29.0/24"

Upvotes: 1

blunova
blunova

Reputation: 2532

Try this:

import pandas as pd

data = pd.read_csv("test.csv", sep=";")

names = data["name"].to_list()
subnets = data["subnet"].to_list()

def process_data(names, subnets):
    for name, subnet in zip(names, subnets):
        print(f"{name}: {subnet}")

if __name__ == "__main__":
    process_data(names, subnets)

Upvotes: 1

Thrasy
Thrasy

Reputation: 606

You should probably use pandas:

import pandas as pd
data = pd.read_csv(csv_address_objects, sep = ';')

You can then easily access columns, lines or any specific value. See: https://pandas.pydata.org/docs/getting_started/intro_tutorials/03_subset_data.html

Upvotes: 0

Related Questions