Sunday, November 17, 2024
Google search engine
HomeLanguagesWrite a dictionary to a file in Python

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:

  • Import Json
  • Create A Dictionary  in-order pass it into text file.
  • Open file in write mode.
  • Use json.dumps() for json string

Code:

Python3




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:

  • Create a dictionary.
  • Open a file in write mode.
  • Here We Use For Loop With Key Value Pair Where “Name”  is Key And  “Alice” is Value So For loop Goes Through Each Key:Value Pair For Each Pairs 
  • Then f.write() Function Just Write’s The Output In Form Of String “%s” 

Code:

Python3




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

Python3




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


Output:

RELATED ARTICLES

Most Popular

Recent Comments