. Advertisement .
..3..
. Advertisement .
..4..
Are you struggling to convert CSV to dictionary in Python? No worry, there are lots of approaches to this common problem. Our article will introduce the four most prevalent ones, suited even to novices. Let’s get started!
How to Convert CSV to Dictionary in Python?
Method 1: Use “CSV” Modules
Python boasts CSV modules encompassing all utility features to control other CSV files (such as writing, reading, insertion, and conversion).
So how can we convert CSV Files into dictionaries? First, navigate to that CSV file to open it. Next, perform tasks to code it into variables via the “reader()” functions. This operation will transform your file into Python objects.
Next, employ your dictionary understanding to change CSV objects into dictionaries by repeating reader objects. Next, access the initial two rows and assign them the role of a key value pair for your dictionary.
Code:
import csv
convertCSV = {}
with open('example-file.csv', mode='r') as inp:
reader = csv.reader(inp)
convertCSV = {columns[0]:columns[3] for columns in reader}
print(convertCSV)
Output:
{'Product': 'Pants', ' Size': ' Medium', ' Color': ' Brown', ' Price': '$23 '}
Here is file example-file.csv when opening with excel:
......... ADVERTISEMENT .........
..8..
Method 2: Use DictReader()
Another tactic is to employ the “DictReader()”, which is also a CSV operation. Since dictionaries serve as key-value data categories, the CSV header (first row) will function as your keys. Meanwhile, the remaining values will get paired with their appropriate keys.
Look at this table. It represents a CSV file that we can activate and parse:
Amount, 2020, 2021, 2022
Mercedes, 235, 315, 443
Tesla, 611, 315, 645
Ferrari, 165, 321, 412
Porsche, 312, 641, 512
BMW, 253, 452, 712
Code:
import csv
with open('example-file.csv', 'r') as file:
reader = csv.DictReader(file, skipinitialspace=True)
for cars in reader:
print(cars)
Output:
{'Amount': 'Mercedes', '2020': '235', '2021': '315', '2022': '443 '}
{'Amount': 'Tesla', '2020': '611', '2021': '315', '2022': '645'}
{'Amount': 'Ferrari', '2020': '165', '2021': '321', '2022': '412'}
{'Amount': 'Porsche', '2020': '312', '2021': '641', '2022': '512'}
{'Amount': 'BMW', '2020': '253', '2021': '452', '2022': '712'}
Method 3: Use “Pandas Read_csv()”
Another tactic is to employ the “Pandas Read_csv()”. Experienced programmers report that they can proceed with much more data than other techniques.
Code:
import pandas as pd
url = "https://raw.githubusercontent.com/LearnPythonWithRune/LearnPython/main/files/demo_Records.csv"
demo_records = pd.read_csv(url)
demo_records = demo_records.to_dict('records')
In the above example, all your data is organized in a long list of dictionary records. As established, this approach helps you read far-off files easily (such as from GitHub). However, one palpable disadvantage is that you might need to download the “pandas” library.
Method 4: Use “This” in A Script
The script will receive an argument (in this case, the CSV file) and deem it as sys.argv before printing out the decoded dictionary list (Please refer to this article for more info on printing out a Python list).
Codes:
#!/usr/bin/env python
import csv
import sys
import pprint
# Function to convert a csv file to a list of dictionaries. Takes in one variable called "variables_file"
def csv_dict_list(variables_file):
# Open variable-based csv, iterate over the rows and map values to a list of dictionaries containing key/value pairs
reader = csv.DictReader(open(variables_file, 'rb'))
dict_list = []
for line in reader:
dict_list.append(line)
return dict_list
# Calls the csv_dict_list function, passing the named csv
device_values = csv_dict_list(sys.argv[1])
# Prints the results nice and pretty like
pprint.pprint(device_values)
The next step is to check it out, delivering the “device-specifics.csv” argument:
/csv_dict_list.py device-specifics.csv
[{'$STR_CRYPTO_KEY': '06Tcqh7WEDeYMDz7F8iA',
'$STR_LOOP': '10.255.192.1',
'$STR_NET': '10.163.1',
'$STR_NUM': '1',
'$TUN_IP': '10.255.140.2'},
{'$STR_CRYPTO_KEY': 'CS7sXm5LWDyZE554l4Ga',
'$STR_LOOP': '10.255.192.2',
'$STR_NET': '10.163.2',
'$STR_NUM': '2',
'$TUN_IP': '10.255.140.3'},
{'$STR_CRYPTO_KEY': 'YdyQ85ThUvUgssxaUc2l',
'$STR_LOOP': '10.255.192.3',
'$STR_NET': '10.163.3',
'$STR_NUM': '3',
'$TUN_IP': '10.255.140.4'},
{'$STR_CRYPTO_KEY': 'orZG0TKrqy098FilZaT2',
'$STR_LOOP': '10.255.192.4',
'$STR_NET': '10.163.4',
'$STR_NUM': '4',
'$TUN_IP': '10.255.140.5'},
{'$STR_CRYPTO_KEY': 'sAvyto9yhXWZm41mijt8',
'$STR_LOOP': '10.255.192.5',
'$STR_NET': '10.163.5',
'$STR_NUM': '5',
'$TUN_IP': '10.255.140.6'},
{'$STR_CRYPTO_KEY': '1xQVsXc94T5b0miSydg2',
'$STR_LOOP': '10.255.192.6',
'$STR_NET': '10.163.6',
'$STR_NUM': '6',
'$TUN_IP': '10.255.140.7'}]
Conclusion
ITtutoria has introduced to you how to convert CSV to dictionary in Python. Examine our examples closely, and you will have no trouble solving this issue (as well as other similar errors). Feel free to contact us for more clarifications if necessary!
Leave a comment