Skip to content
Advertisement

Python List to Dictionary from a file

I have a file of notes that im trying to convert to a dictionary. I got the script working but failed to output the data im looking for when there are repeated values.

In short took the file commands or comments which are separated by # as per below. I take that list and seperate the 1st column “key” by # and the rest is the comment or definition. Then i check the magic word im looking for, parse it match it and then to out.

Flashcards file as per below

JavaScript

Again it works but when i search for car nissan. I get four responses but i only get the last “rougue” output or i get 4 repeated response “rougue”.

what’s the best way to accomplish this?

Advertisement

Answer

If you may have repeated elements then you should always use lists to keep even single value

JavaScript

instead of

JavaScript

EDIT:

Full working code with other changes

  • first I used shorter and more readable names for variables,
  • I read file at start and later use loop to ask for different cards.
  • I added command !keys to display all keys, and !exit to exit loop and finish program,
  • list(sorted(flashcards.keys())) gives all keys from dictionary without repeating values (and sorted)

I used io only to simulate file in memory – so everyone can simply copy and run this code (without creating file FlashCards) but you should use open(...)

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement