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.
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.)
Thank you, not entirely sure what is happening on lines #4 and #5?
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}