Write a dictionary to a file in Python Read Courses Practice Improve Improve Improve Like Article Like Save Article Save Report issue Report 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: Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century. Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve. Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore. Last Updated : 29 Dec, 2020 Like Article Save Article Previous How to Read Text File Into List in Python? Next Compute the histogram of nums against the bins using NumPy Share your thoughts in the comments Add Your Comment Please Login to comment...