A
A
Artem Melnykov2020-09-23 12:02:31
Python
Artem Melnykov, 2020-09-23 12:02:31

How to get data by 1 parameter from CSV?

I have this csv file:

name|id|nick
Test1|1|@test1
Test2|2|@test2
Test3|3|@test3

And how can I get all the parameters of a person by his id in Python, i.e. I enter 1 into the program and it gives out the name and nickname that match id 1

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Kuts, 2020-09-23
@NickProgramm

import csv

ID = 1

with open('users.csv') as csvfile:
    reader = csv.DictReader(csvfile, delimiter='|')
    for row in reader:
        if int(row['id']) == ID:
            print(f'{row["name"]} {row["nick"]}')

Z
zexer, 2020-09-23
@zexer

Can you do it like this

import pandas as pd

data = pd.read_csv('list.csv', sep=';')


def get_user_by_id(id, data):
    data = data.loc[data['id'] == id, ['nick', 'name']]
    name = data['name'][0]
    nick = data['nick'][0]
    return {'name': name, 'nick': nick}


print(get_user_by_id(1, data))
# Out: {'name': 'Test1', 'nick': '@test1'}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question