Open In App

Write a dictionary to a file in Python

Dictionary is used to store data values in the form of key:value pairs. In this article we will see how to write dictionary into a file. Actually we can only write a string to a file. If we want to write a dictionary object, we either need to convert it into string using json or serialize it.

Method:1 Storing Dictionary With Object Using Json



Approach:

Code:






import json
  
details = {'Name': "Bob",
          'Age' :28}
  
with open('convert.txt', 'w') as convert_file:
     convert_file.write(json.dumps(details))

Output:

Method 2: Using Loop

Approach:

Code:




details={'Name' : "Alice",
         'Age' : 21,
         'Degree' : "Bachelor Cse",
         'University' : "Northeastern Univ"}
  
with open("myfile.txt", 'w') as f: 
    for key, value in details.items(): 
        f.write('%s:%s\n' % (key, value))

Output:

Method:3 Without Using loads(),dumps().

Here The Steps Are Followed Above Methods But in Write We Use Str() Method Which Will Convert The Given Dictionary Into String




details = {'Name': "Bob", 'Age' :28
  
with open('file.txt','w') as data: 
      data.write(str(details))

Output:


Article Tags :