vik1245
vik1245

Reputation: 556

Python Writing a Dictionary to Text File isn't producing correct output

I have a dictionary as such -

d = {"Dave":("Male", "96"), "Alice":("Female", "98")}

I want to write it to a text file in such a format -

Dave
Male
96
Alice
Female
98

This is my current code -

d = {"Dave":("Male", "96"), "Alice":("Female", "98")}

with open("dictionary.txt", 'w') as f:
    for key, value in d.items():
    f.write('%s \n %s \n' % (key, value))

It is, however, producing the following output in the text file:

Dave 
  ('Male', '96') 
 Alice 
  ('Female', '98') 

How can I adjust this? Please help! Thanks.

Upvotes: 0

Views: 210

Answers (4)

Tom Lynch
Tom Lynch

Reputation: 913

The following works in Python 3.6:

d = {"Dave":("Male", "96"), "Alice":("Female", "98")}
with open('dictionary.txt', mode='w') as f:
    for name, (sex, age) in d.items():
        f.write(f'{name}\n{sex}\n{age}\n')

You can unpack the tuple at the top of the for loop. Additionally, in Python 3.6, you can use the f-string mechanism to directly interpolate variable values into strings.

Upvotes: 1

Mohamad Ibrahim
Mohamad Ibrahim

Reputation: 5575

 d = {"Dave":("Male", "96"), "Alice":("Female", "98")}
 with open("dictionary.txt", 'w') as f:
    for key in d.keys():
        f.write('%s \n' % (key))
        for v in d[key]:
           f.write('%s \n' % (v))

Upvotes: 0

Jean-François Fabre
Jean-François Fabre

Reputation: 140316

When you convert a tuple to a str using formatting, you get the representation of the tuple, which is (roughly, there are 2 methods __str__ and __repr__ actually) what python prints when you print the item in the console.

To get elements without the tuple decorations, you have to unpack the tuple. One option (using format):

for key, value in d.items():
    f.write("{}\n{}\n{}\n".format(key,*value))

* unpacks the elements of value into 2 elements. format does the rest

An even more compact way would be to multiply the format string by 3 (less copy/paste)

for key, value in d.items():
    f.write(("{}\n"*3).format(key,*value))

Upvotes: 2

vik1245
vik1245

Reputation: 556

I used the i in range method that iterates for every value in every key -

d = {"Dave":("Male", "96"), "Alice":("Female", "98")}

with open("dictionary.txt", 'w') as f:
    for key, value in d.items():
        for x in range(0,2):
            f.write('%s \n %s \n' % (key, value[x]))

Upvotes: 1

Related Questions