Kunal Telangi
Kunal Telangi

Reputation: 15

Writing a dictionary to file only results in keys

In this program the output is only showing key but what can i do so that both key and value save in data.txt file

myfile = open(r'data.txt','w')
d = {'studentName':'ABC''\n','RollNo':'2'}
myfile.writelines(d)
myfile.close()

Upvotes: 0

Views: 151

Answers (3)

nabroleonx
nabroleonx

Reputation: 96

d = {'studentName':'ABC', 'RollNo':'2'}

with open('data.txt', 'w') as f:
    for key, value in d.items():
        f.write(f'{key} : {value} \n')

Upvotes: 0

user11578023
user11578023

Reputation:

try this

d = {'studentName': 'ABC''\n', 'RollNo': '2'}
with open("data.txt", 'w') as f:
    for key, value in d.items():
        f.write('%s:%s' % (key, value))

will give

studentName:ABC
RollNo:2

Upvotes: 0

azro
azro

Reputation: 54148

The best way to serialize this, is to use the JSON format, the content would be the following, and use json.loads you'd be able to deserialize the structure in a dict

import json

d = {'studentName': 'ABC', 'RollNo': '2'}
with open(r'data.txt', 'w') as myfile:
    myfile.write(json.dumps(d))

# outputs
{"studentName": "ABC", "RollNo": "2"}

For a custom row by row format, iterate and write each

d = {'studentName': 'ABC', 'RollNo': '2'}
with open(r'data.txt', 'w') as myfile:
    for k, v in d.items():
        myfile.write(f"{k}:{v}\n")

# outputs
studentName:ABC
RollNo:2

Upvotes: 2

Related Questions