2
dictionary = {}
name = input("Name: ")

while name: #while the name is not blank
    age = input("Age: ")
    dictionary[name] = age
    name = input("Name: ")

print("Thank you, bye!")

f = open("1ex.txt","w")
f.write( str(dictionary) )
f.close()

So I have this code, it does what I want, but I cant seems to figure it out how can I write the file, so that it would have not a dictionary, but smth like this:

Jane, 25
Jim, 24

I tried putting everything into a list, but it doesn't work out for me.

CDJB
  • 14,043
  • 5
  • 29
  • 55
Liviosah
  • 325
  • 2
  • 11
  • If you want it saved as a csv you could use this https://stackoverflow.com/questions/8685809/writing-a-dictionary-to-a-csv-file-with-one-line-for-every-key-value – Buckeye14Guy Nov 15 '19 at 14:43

1 Answers1

1

Try this:

dictionary = {}
name = input("Name: ")

while name: #while the name is not blank
    age = input("Age: ")
    dictionary[name] = age
    name = input("Name: ")

print("Thank you, bye!")

# Open the file
with open("1ex.txt","w") as f:
    # For each key/value pair in the dictionary:
    for k, v in dictionary.items():
        # Write the required string and a newline character
        f.write(f"{k}, {v}\n")
CDJB
  • 14,043
  • 5
  • 29
  • 55