When it comes to converting CSV files into a usable format, working with them can be a challenge. You can quickly access and organize data by converting a CSV file to a Python dictionary. Fortunately, Python makes it easy to convert CSV files into a dictionary, allowing you to quickly and easily manipulate the data in whatever way you need. This page will walk you through the process of converting a CSV file into a Python dictionary, so you can get the most out of your data.
The following approaches will be demonstrated with an example to convert CSV to the dictionary in Python:
- using to_dict() approach
- DictReader() approach
- Dict comprehension approach to convert CSV into the dictionary in Python.
*Working on Jupyter Notebook Anaconda Environment, Python version 3+.
If you want to learn more about Python Programming, visit Python Programming Tutorials.
Read a CSV file in Python
Reading a CSV file is an easy task. And pandas library makes the task easier for programmers. By importing a pandas library the task to read a CSV file in Python becomes a computationally easier and fast approach.
- You just import the pandas module from the library
- And using pd.read_csv() you can read any CSV file in Python.
- Within pd.read_csv() function pass the path of the CSV file or directory.
- file.head() command returns 5 rows from the file, and if set to 2 it returns the 2 rows from the file only and skips the rest.
import pandas as pd
import numpy as np
file=pd.read_csv(r"ICC MEN'S HIGH SCORES.csv")
rows=file.head(2) #returns two rows
print(rows)
print('\n')
File.columns #returns information about labels
Player Runs Balls 4s 6s SR Unnamed: 6 Team \
0 Fakhar Zaman 193 155 18 10 124.51 NaN Pakistan
1 JN Malan 177* 169 16 6 104.73 NaN South Africa
Opposition Ground Match Date Scorecard
0 v South Africa Johannesburg 04-Apr-21 ODI # 4286
1 v Ireland Dublin (Malahide) 16-Jul-21 ODI # 4305
Convert CSV Into a Dictionary in Python using the to_dict() approach
Converting a CSV Into a Dictionary in Python is possible using the to_dict() method. Here’s how the following example executes:
- Import necessary libraries
- Provide a path for the CSV file within pd.read_csv(), then using (.) operator convert the csv file to dictionary using to_dict() approach.
- Save the output in a new variable and print them. The output clearly shows that the CSV file is pretty printed into the dictionary.
import csv
import pandas as pd
import numpy as np
csv2dict = pd.read_csv("ICC MEN'S HIGH SCORES.csv").to_dict()
print(csv2dict)
{'Player': {0: 'Fakhar Zaman', 1: 'JN Malan', 2: 'JC Buttler', 3: 'Ibrahim Zadran', 4: 'Babar Azam'}, 'Runs': {0: '193', 1: '177*', 2: '162*', 3: '162', 4: '158'}, 'Balls': {0: 155, 1: 169, 2: 70, 3: 138, 4: 139}, '4s': {0: 18, 1: 16, 2: 7, 3: 15, 4: 14}, '6s': {0: 10, 1: 6, 2: 14, 3: 4, 4: 4}, 'SR': {0: 124.51, 1: 104.73, 2: 231.42, 3: 117.39, 4: 113.66}, 'Unnamed: 6': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan}, 'Team': {0: 'Pakistan', 1: 'South Africa', 2: 'England', 3: 'Afghanistan', 4: 'Pakistan'}, 'Opposition': {0: 'v South Africa', 1: 'v Ireland', 2: 'v Netherlands', 3: 'v Sri Lanka', 4: 'v England'}, 'Ground': {0: 'Johannesburg', 1: 'Dublin (Malahide)', 2: 'Amstelveen', 3: 'Pallekele', 4: 'Birmingham'}, 'Match Date': {0: '04-Apr-21', 1: '16-Jul-21', 2: '17-Jun-22', 3: '30-Nov-22', 4: '13-Jul-21'}, 'Scorecard': {0: 'ODI # 4286', 1: 'ODI # 4305', 2: 'ODI # 4413', 3: 'ODI # 4490', 4: 'ODI # 4303'}}
DictReader() function to convert CSV files into DICT format
DictReader() will be another approach to converting CSV files into dictionaries in Python. Dictionaries consist of a key-vales when the CSV file is converted to the dictionary, the columns’ attributes become the header and values will pair according to the keys.
Here’s how it executes:
- Import necessary libraries
- Using the open() command read the CSV file and use with…as store the CSV file into a variable “file”, in our case.
- Now convert the CSV file into a dictionary using DictReader(file)
- This will convert the CSV file into a dictionary
- For..in structure iterates over the CSV file until and unless the last key-value pair is converted.
import csv
with open("ICC MEN'S HIGH SCORES.csv", 'r') as file:
csv2dict = csv.DictReader(file)
for i in csv2dict:
print(i)
{'Player': 'Fakhar Zaman', 'Runs': '193', 'Balls': '155', '4s': '18', '6s': '10', 'SR': '124.51', '': '', 'Team': 'Pakistan', 'Opposition': 'v South Africa', 'Ground': 'Johannesburg', 'Match Date': '04-Apr-21', 'Scorecard': 'ODI # 4286'}
{'Player': 'JN Malan', 'Runs': '177*', 'Balls': '169', '4s': '16', '6s': '6', 'SR': '104.73', '': '', 'Team': 'South Africa', 'Opposition': 'v Ireland', 'Ground': 'Dublin (Malahide)', 'Match Date': '16-Jul-21', 'Scorecard': 'ODI # 4305'}
{'Player': 'JC Buttler', 'Runs': '162*', 'Balls': '70', '4s': '7', '6s': '14', 'SR': '231.42', '': '', 'Team': 'England', 'Opposition': 'v Netherlands', 'Ground': 'Amstelveen', 'Match Date': '17-Jun-22', 'Scorecard': 'ODI # 4413'}
{'Player': 'Ibrahim Zadran', 'Runs': '162', 'Balls': '138', '4s': '15', '6s': '4', 'SR': '117.39', '': '', 'Team': 'Afghanistan', 'Opposition': 'v Sri Lanka', 'Ground': 'Pallekele', 'Match Date': '30-Nov-22', 'Scorecard': 'ODI # 4490'}
{'Player': 'Babar Azam', 'Runs': '158', 'Balls': '139', '4s': '14', '6s': '4', 'SR': '113.66', '': '', 'Team': 'Pakistan', 'Opposition': 'v England', 'Ground': 'Birmingham', 'Match Date': '13-Jul-21', 'Scorecard': 'ODI # 4303'}
Dict comprehension approach to convert CSV into the dictionary in Python.
Using on-liner dict comprehension approach it becomes possible to convert the CSV file to the dictionary. Using dict comprehension approach in aggregation with the reader() function will help to accomplish this task.
Here’s how it works!
- Import necessary libraries
- Using open() read the file from the local directory and save it using with…as an approach. It will store the CSV file in the variable ”file”.
- reader() read the file and store it in a new object.
- Now using dict comprehension approach converts the created CSV object to the dictionary in a one-liner pythonic approach.
- This will returns the first two columns on display. As shown in the example code output.
import csv
dict_from_csv = {}
with open("ICC MEN'S HIGH SCORES.csv",'r') as file:
csv2dict = csv.reader(file)
csv2dict = {rows[0]:rows[1] for rows in csv2dict}
print(csv2dict)
{'Player': 'Runs', 'Fakhar Zaman': '193', 'JN Malan': '177*', 'JC Buttler': '162*', 'Ibrahim Zadran': '162', 'Babar Azam': '158'}
Conclusion
If you are working with a large amount of data, it can be helpful to store it in a CSV (comma-separated values) file. However, if you need to convert that data into a Python dictionary, this page demonstrates methods on how to quickly and easily convert a CSV file into a Python dictionary. Grab the one that fits your problem.