Notification texts go here Contact Us Buy Now!

Creating a dictionary from a csv file?

To Create a dictionary from a csv file:

  • Approach 1:
import csv
reader = csv.reader(open('filename.csv', 'r'))
d = {}
for row in reader:
   k, v = row
   d[k] = v
  • Import the CSV module.
  • Open the CSV file in read mode using the open() function.
  • Create a CSV reader object using the csv.reader() function.
  • Create an empty dictionary to store the data.
  • Iterate over the rows in the CSV file using a for loop.
  • For each row, extract the key and value using the row[0] and row[1] indexes.
  • Add the key-value pair to the dictionary using the k and v variables.
  • Approach 2:
import csv

with open('coors.csv', mode='r') as infile:
    reader = csv.reader(infile)
    with open('coors_new.csv', mode='w') as outfile:
        writer = csv.writer(outfile)
        mydict = {rows[0]:rows[1] for rows in reader}
  • Here, the code uses context manager to open, read and close the CSV files.
  • The code creates a dictionary comprehension to convert the CSV data to a dictionary.
  • Approach 3:
import csv
from collections import defaultdict

my_dict = defaultdict(list)

with open('filename.csv', 'r') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    for line in csv_reader:
        for key, value in line.items():
            my_dict[key].append(value)
  • Using defaultdict avoids the need to check if the key exists and also append the value to the list.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.