(this is my first post on SO, so please let me know if this isn't proper formatting!)
I'm making a form that'll pull the name when given an ID number from a CSV file and have absolutely no idea where to start.
Example Data:
ID Number | Name |
---|---|
1 | John Doe |
2 | Jane Shmoe |
3 | Kane Foe |
So if I input the ID number "1", it'll output "Jane Doe"
Thanks
CodePudding user response:
Use DictReader
from csv
module and create a dictionary of your data:
import csv
with open('data.csv') as csvfile:
reader = csv.DictReader(csvfile)
data = {d['ID Number']: d['Name'] for d in list(reader)}
num = input('Input an ID Number: ')
print(data.get(num, 'Not found'))
Output:
Input an ID Number: 1
John Doe
CodePudding user response:
I would do this based on subsetting. Start by reading in the data as a pandas dataframe:
import pandas as pd
df = pd.read_csv("<filename>.csv")
From here you want to query your name column by the id, so (as an example) if you want to find the name associated with ID = 1:
result = df[df["ID Number"] == 1]]
CodePudding user response:
You can load the csv into a dictionary, then repeatedly ask the user for input:
file = open("example.csv", "r")
d = {}
for line in file:
split = line.strip().split(",")
d[split[0]] = split[1]
while True:
id = input("Please input an ID: ")
print(d[id])
Output:
Please input an ID: 1
Jane Doe
Please input an ID: 3
Kane Foe
Please input an ID: 2
Jane Shmoe
CodePudding user response:
Here is a hint on how you have to do it using panda:
import pandas as pd
df = pd.read_csv('sample.csv')
user=df[df['ID Number']==2].iloc[0]
print(user.to_dict())
In this example, we were looking for the users with id of 2. Then we choose the first item found. The next step, we convert it to dictionary and print it.
You can use different function to read in Command line interface, such as input (https://www.geeksforgeeks.org/taking-input-in-python/).