Python Forum
How do you import a dictionary from a .csv file?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do you import a dictionary from a .csv file?
#1
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?
Reply
#2
(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'] '☇'
Reply
#3
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Video doing data treatment on a file import-parsing a variable EmBeck87 15 2,855 Apr-17-2023, 06:54 PM
Last Post: EmBeck87
  Import XML file directly into Excel spreadsheet demdej 0 839 Jan-24-2023, 02:48 PM
Last Post: demdej
Question How do I skipkeys on json file read to python dictionary? BrandonKastning 3 1,886 Mar-08-2022, 09:34 PM
Last Post: BrandonKastning
  trying to write a dictionary in a csv file CompleteNewb 13 6,580 Mar-04-2022, 04:43 AM
Last Post: deanhystad
  How from sklearn.datasets import load_diabetes change to import to CSV file Anldra12 0 1,853 Dec-25-2021, 07:20 PM
Last Post: Anldra12
  How to import file and function in another folder SriRajesh 1 3,154 Dec-18-2021, 08:35 AM
Last Post: Gribouillis
  Python - Import file sequence into Media Pool jensenni 1 2,130 Feb-02-2021, 05:11 PM
Last Post: buran
Smile Import error with local file colt 1 1,930 Nov-08-2020, 07:56 AM
Last Post: Gribouillis
  saving a dictionary as json file vinay_py 6 3,090 Jun-06-2020, 05:07 PM
Last Post: vinay_py
  Code import .CSV file to MySQL table rtakle 4 2,854 Apr-30-2020, 03:16 PM
Last Post: anbu23

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020