Python Forum
Converting data in CSV and TXT to dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Converting data in CSV and TXT to dictionary
#1
Hi

I have data in data.csv and data.txt that I want to convert to a python3 dictionary via code, without the use of Pandas.

Is this possible? I have been googling but a lot inevitably go off into the realm of Pandas.
Reply
#2
Sure, but it depends on the data. There is no single way to represent key/value pairs in a txt or csv.

Read the file in and split() or parse however you want so you you've got the key and the value.
Then assign them in a loop over each part in the file. A simple one might be something like:

dictionary = {}
with open("foo.csv") as f:
    for line in f:
        key, value = f.rstrip().split(",")
        dictionary[key] = value
You might need to use the CSV module if you have complex delimiters (Quoted elements, etc.)
Reply
#3
Thank you, not entirely sure what is happening on lines #4 and #5?
Reply
#4
Line 4 takes the information on one line of the file and attempts to read it as two pieces of data (a "key" and a "value"). Depending on the format of the file, this might have to be changed to gather the correct information.

Line 5 is one way of populating a dict. It sets the entry for "key" to be "value". You can print out the dictionary afterward and see the information.

>>> dictionary = {}
>>> dictionary["key"] = "value"
>>> dictionary["A"] = 5
>>> print(dictionary)
{'key': 'value', 'A': 5}
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Matching Data - Help - Dictionary manuel174102 1 354 Feb-02-2024, 04:47 PM
Last Post: deanhystad
  Converting '1a2b3c' string to Dictionary PythonNoobLvl1 6 1,779 May-13-2022, 03:44 PM
Last Post: deanhystad
  [SOLVED] Concat data from dictionary? Winfried 4 1,666 Mar-30-2022, 02:55 PM
Last Post: Winfried
  Python, how to manage multiple data in list or dictionary with calculations and FIFO Mikeardy 8 2,523 Dec-31-2021, 07:47 AM
Last Post: Mikeardy
  Converting data object mbrown009 5 2,718 May-30-2021, 11:35 PM
Last Post: mbrown009
  Beautify dictionary without converting to string. sharoon 6 3,297 Apr-11-2021, 08:32 AM
Last Post: buran
  Issue accessing data from Dictionary/List in the right format LuisSatch 2 2,169 Jul-25-2020, 06:12 AM
Last Post: LuisSatch
  problem coverting string data file to dictionary AKNL 22 6,265 Mar-10-2020, 01:27 PM
Last Post: AKNL
  Converting query string as a condition for filter data. shah_entrance 1 1,750 Jan-14-2020, 09:22 AM
Last Post: perfringo
  Read csv file, parse data, and store in a dictionary markellefultz20 4 4,486 Nov-26-2019, 03:33 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

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