Python Forum

Full Version: How do you import a dictionary from a .csv file?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a .csv file like this

data.csv
h:ᛄ
j:☆
k:☇
and I have a python program

import csv
f=open('data.csv','r')
reader=csv.Reader(f)
dict={}
how can I import this .csv into my dict especially when it has special characters?
(Jul-27-2019, 01:22 PM)SteampunkMaverick12 Wrote: [ -> ]how can I import this .csv into my dict especially when it has special characters?
Read in with utf-8,once in inside it's a normal string(Unicode) as Python 3 has made big changes to Unicode.
import csv

with open('data.csv', encoding='utf-8') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=':')
    my_dict =  dict([row for row in csv_reader])

print(my_dict)
Output:
{'h': 'ᛄ', 'j': '☆', 'k': '☇'} >>> my_dict['k'] '☇'
Hi, As per my knowledge i am sharing you simple syntax to import a directory a CSV file.

import csv
data = csv.reader(open('data.csv'))

fields = data.next()
for row in data:
       
    items = zip(fields, row)
    item = {}
     
    for (name, value) in items:
        item[name] = value.strip() 
By following above syntax you can import data from .CSV file. I hope this will help you.