0

I have just started learning Python and I have created a simple dictionary with a text editor

Spain Spanien
Germany Deutschland
Sweden Schweden
France Frankreich
Greece Griechenland
Italy Italien

The dictionary is called worterbuch.txt. I can read it with a python program called worterbuch.py

woerter={}
fobj = open("woerterbuch.txt", "r")
for line in fobj:
    print(line)
fobj.close

This gives the content of the text file as an output. It seems simple enough. Is there a simple way to do the reverse, i.e. create the text file by typing the text in Python and telling the program to create a dictionary from it? What I have tried is

woerter={}
fobj=open("dict.txt", "w") 
woerter={"Germany", "Deutschland",
         "Italy", "Italien"} 
fobj.close() 

but this produces just an empty dict.txt file.

Nick
  • 3
  • 2
  • 1
    What @JETM said, but more specifically this [Answer](https://stackoverflow.com/a/46137768/929999) – Torxed Oct 17 '18 at 11:14
  • It seems the term "dictionary" is misleading you. He meant an actual "dictionary", not the python data structure =). – Montenegrodr Oct 17 '18 at 11:18

1 Answers1

0

You were close. Try this:

woerter = ["Germany Deutschland", "Italy Italien"]
content = '\n'.join(woerter)

fobj=open("dict.txt", "w") 
fobj.write(content)
fobj.close() 

But I'd go with a more pythonic way like:

woerter = ["Germany Deutschland", "Italy Italien"]

with open("dict.txt", "w") as  fobj:
    fobj.write('\n'.join(woerter))
Montenegrodr
  • 1,597
  • 1
  • 16
  • 30