Python Forum
Converting data in CSV and TXT to dictionary - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Converting data in CSV and TXT to dictionary (/thread-31610.html)



Converting data in CSV and TXT to dictionary - kam_uk - Dec-22-2020

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.


RE: Converting data in CSV and TXT to dictionary - bowlofred - Dec-22-2020

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.)


RE: Converting data in CSV and TXT to dictionary - kam_uk - Dec-22-2020

Thank you, not entirely sure what is happening on lines #4 and #5?


RE: Converting data in CSV and TXT to dictionary - bowlofred - Dec-22-2020

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}