![]() |
|
[Tut] Convert CSV to List of Tuples in Python - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Convert CSV to List of Tuples in Python (/thread-99625.html) |
[Tut] Convert CSV to List of Tuples in Python - xSicKxBot - 06-23-2022 Convert CSV to List of Tuples in Python 4.5/5 – (2 votes) ![]() Problem Formulation Given a CSV file (e.g., stored in the file with name Code: 'my_file.csv'Code: INPUT: file 'my_file.csv'
9,8,7
6,5,4
3,2,1Challenge: How to convert the CSV file to a list of tuples, i.e., putting the row values into the inner tuples? Code: OUTPUT: Python list of tuples
[(9, 8, 7), (6, 5, 4), (3, 2, 1)]![]() Method 1: csv.reader() To convert a CSV file Code: 'my_file.csv'Code: csv.reader(file_obj)Code: list(tuple(line) for line in reader)Here’s a simple example that converts our CSV file to a nested list using this approach: Code: import csv csv_filename = 'my_file.csv' with open(csv_filename) as f: reader = csv.reader(f) lst = list(tuple(line) for line in reader)Output: Code: print(lst)
# [('9', '8', '7'), ('6', '5', '4'), ('3', '2', '1')]![]() Method 2: One-Liner You can also convert a CSV to a list of tuples using the following Python one-liner idea: Open the file using Code: open()Code: csv.reader()Code: list()Here’s how that looks: Code: import csv; lst=list(tuple(line) for line in csv.reader(open('my_file.csv'))); print(lst)Concise, isn’t it? ![]() The output is the same: Code: [('9', '8', '7'), ('6', '5', '4'), ('3', '2', '1')]By the way: Do you need all inner elements converted to a certain data type such as integer? If so, use the following approach on top of the previously shown list Code: lstCode: new_lst = [tuple(int(x) for x in inner) for inner in lst]The converted Code: new_lstCode: print(new_lst)
# [('9', '8', '7'), ('6', '5', '4'), ('3', '2', '1')]![]() Method 3: Pandas You can convert a CSV to a list of tuples with Pandas by first readingthe CSV without header line using Code: pd.read_csv('my_file.csv', header=None)Code: df.values.tolist()Here’s an example that converts the CSV to a Pandas DataFrame and then to a nested raw Python list and then to a list of tuples: Code: import pandas as pd # CSV to DataFrame
df = pd.read_csv('my_file.csv', header=None) # DataFrame to List of Lists
lst = df.values.tolist() # List of Lists to List of Tuples:
new_lst = [tuple(x) for x in lst] print(new_lst)
# [(9, 8, 7), (6, 5, 4), (3, 2, 1)]This was easy, wasn’t it? ![]() Of course, you can also one-linerize it by chaining commands like so: Code: # One-Liner to convert CSV to list of tuples:
lst = [tuple(x) for x in pd.read_csv('my_file.csv', header=None).values.tolist()]![]() Method 4: Raw Python No Dependency If you’re like me, you try to avoid using dependencies if they are not needed. Raw Python is often more efficient and simple enough anyways. Also, you don’t open yourself up to unnecessary risks and complexities. Question: So, is there a simple way to read a CSV to a list of tuples in raw Python without external dependencies? Sure! To read a CSV to a list of tuples in pure Python, open the file using Code: open('my_file.csv')Code: f.readlines()Code: strip()Code: ','Code: split(',')Code: tuple()You can accomplish this in a simple list comprehension statement like so: Code: csv_filename = 'my_file.csv' with open(csv_filename) as f: lines = f.readlines() lst = [tuple(line.strip().split(',')) for line in lines] print(lst)Feel free to check out my detailed video in case you need a refresher on the powerful Python concept list comprehension: Related Tutorial: Understanding List Comprehension in Python.![]() Become a One-Liner Wizard! In case you enjoyed the one-liners presented here and you want to improve your Python skills, feel free to get yourself a copy of my best-selling Python book: Python One-Liners Book: Master the Single Line First! Python programmers will improve their computer science skills with these useful one-liners. ![]() Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert. The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line. Get your Python One-Liners on Amazon!! |