0

I have a txt file that I want to convert into a dictionary but I'm not sure how. All of the examples I can find each key only has one value but my dictionary has multiple values per key.

my txt file looks like this.

{'Morning' : ['Amox-Clav' , 'Cetirizine' , 'Acetaminophen'],'Afternoon' : ['Vitamin D' , 'Dextromethorphan'] ,'Night' : ['Amox-Clav' , 'Acetaminophen'],}

So I need to both open this txt file and convert the strings into a dictionary.

  • 1
    There's effectively only one value per key here. In this case, the "one" is a list, and in that list yes there are multiple items, but you still have a one-to-one mapping of one key to one list. What do all of the examples suggest you do? I would recommend using `json.load(file)` in this case. – Kraigolas Jan 06 '22 at 03:18
  • 1
    Your text file looks like a malformed .json format - where is the text file coming from? Do you have any control over how the text file gets created? (not that just using `json.load` won't work on this file, as it doesn't use double quotes and has spare commas) – Grismar Jan 06 '22 at 03:36
  • I voted to reopen, because the linked question is about turning a list representation of a string into a Python list and this question is regarding a dictionary and it's not even clear that the data can only be transmitted as a string representation of a Python type. – Grismar Jan 06 '22 at 03:39
  • Why does the TXT file have quotes around the entire thing? Or did you add those when you were writing the question? For future reference, see the formatting help page: [code formatting](/editing-help#code). – wjandrea Jan 06 '22 at 03:40
  • There seems to be a typo: `'Dextromethorphan` with no closing quote. – wjandrea Jan 06 '22 at 03:42
  • I closed the question because it seems like the actual data is valid Python source code, even though the quotes as written here are wonky. If I'm incorrect, please [edit] your desired output into the question and LMK. – wjandrea Jan 06 '22 at 03:47
  • @Grismar The top answer still applies whether it's a list or dict: `ast.literal_eval()`. I don't disagree with your other point, but I'd like to see OP clarify this question before reopening. – wjandrea Jan 06 '22 at 03:50
  • I am in a python class and we have been given absolutely no direction on how to format the file or how to format each dictionary item as a text string in the input file or how to convert each input string into a dictionary item. I have tried multiple things but nothing I've done has seemed to work. – tmjohnson112341 Jan 06 '22 at 03:56

0 Answers0