How to write dict to file python

How to Write Python Dictionary to File

To write a dictionary to a file in Python, there are a few ways you can do it depending on how you want the dictionary written.

If you want to write a dictionary just as you’d see it if you printed it to the console, you can convert the dictionary to a string and output it to a text file.

dictionary = with open('example.txt', 'w') as f: f.write(str(dictionary))

This is the same as if you wanted to store the dictionary as JSON in a text file with the json.dumps().

import json dictionary = with open('example.txt', 'w') as f: f.write(json.dumps(dictionary))

If you want to write a dictionary as a comma delimited file with the keys and values in separate columns, you can do the following.

import json dictionary = with open('example.csv', 'w') as f: for k, v in dictionary.items(): f.write(str(k) + "," + str(v))

When working with data in your programs, the ability to easily be able to output to files in a readable way is valuable.

One such case is if you have a dictionary variable and you want to write to a file.

There are a few ways you can write a dictionary to a file depending on how you want the dictionary written.

To write a dictionary just as you’d see it if you printed it to the console, you can convert the dictionary to a string and output it to a text file.

Below shows you how you can simply write a dictionary to a file in Python.

dictionary = with open('example.txt', 'w') as f: f.write(str(dictionary))

Writing Dictionary to File with json.dumps() in Python

If you want to write a dictionary to a file as JSON, then you can use the json module dumps() function.

dumps() converts dictionaries into JSON strings. If you write a dictionary to a file with json.dumps(), you can then load it with json.loads() at a later time.

Below shows you how to use the json module to write a dictionary to a file in Python.

import json dictionary = with open('example.txt', 'w') as f: f.write(json.dumps(dictionary))

Writing Dictionary Variable to .csv File in Python

One last way you can write a dictionary variable to a file is if you want to create a comma separated file with keys and values separated by commas.

To do this, you can use the dictionary items() function to get each key/value pair in the dictionary and write on their own line with a comma in between.

Below shows how you can make a csv file from a dictionary in Python.

import json dictionary = with open('example.csv', 'w') as f: f.write("key,value") for k, v in dictionary.items(): f.write(str(k) + "," + str(v))

Hopefully this article has been useful for you to learn how to write dictionary variables to files in Python.

Читайте также:  Символ перевода каретки html
  • 1. Using Matplotlib and Seaborn to Create Pie Chart in Python
  • 2. How to Split List in Half Using Python
  • 3. Python Indicator Function – Apply Indicator Function to List of Numbers
  • 4. How to Read CSV File from AWS S3 Bucket Using Python
  • 5. Using Python to Count Even Numbers in List
  • 6. Remove Leading and Trailing Characters from String with strip() in Python
  • 7. Python Even or Odd – Check if Number is Even or Odd Using % Operator
  • 8. Pascal’s Triangle in Python
  • 9. Print Time Elapsed in Python
  • 10. How to Rotate String in Python

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Источник

Python Save Dictionary To File

In this lesson, you’ll learn how to save a dictionary to a file in Python. Also, we’ll see how to read the same dictionary from a file.

In this lesson, you’ll learn how to:

  • Use the pickle module to save the dictionary object to a file.
  • Save the dictionary to a text file.
  • Use the dump() method of a json module to write a dictionary in a json file.
  • Write the dictionary to a CSV file.

Table of contents

How to save a dictionary to file in Python

Dictionaries are ordered collections of unique values stored in (Key-Value) pairs. The below steps show how to use the pickle module to save the dictionary to a file.

    Import pickle module The pickle module is used for serializing and de-serializing a Python object structure.

Pickling” is the process whereby a Python object is converted into a byte stream, and “unpickling” is the inverse operation whereby a byte stream (from a binary file) is converted back into an original object.

Example: save a dictionary to file

Let’s see the below example of how you can use the pickle module to save a dictionary to a person_data.pkl file.

import pickle # create a dictionary using <> person = print('Person dictionary') print(person) # save dictionary to person_data.pkl file with open('person_data.pkl', 'wb') as fp: pickle.dump(person, fp) print('dictionary saved successfully to file')
Person dictionary dictionary saved successfully to file

Read Dictionary from a File

Now read the same dictionary from a file using a pickle module’s load() method.

import pickle # Read dictionary pkl file with open('person_data.pkl', 'rb') as fp: person = pickle.load(fp) print('Person dictionary') print(person)

Save a dictionary to a text file using the json module

We can use the Python json module to write dictionary objects as text data into the file. This module provides methods to encode and decode data in JSON and text formats.

We will use the following two methods of a json module.

  • The dump() method is used to write Python objects as JSON formatted data into a file.
  • Using the load() method, we can read JSON data from text, JSON, or a binary file to a dictionary object.

Let’s see the below example of how you can use the json module to save a dictionary to a text file.

import json # assume you have the following dictionary person = print('Person dictionary') print(person) print("Started writing dictionary to a file") with open("person.txt", "w") as fp: json.dump(person, fp) # encode dict into JSON print("Done writing dict into .txt file")
Person dictionary Started writing dictionary to a file Done writing dict into .txt file

Person text file

Note: You can also use the dump() method to write a dictionary in a json file. Only you need to change the file extension to json while writing it.

Читайте также:  line-height

Read a dictionary from a text file.

Now, let’s see how to read the same dictionary from the file using the load() function.

import json # Open the file for reading with open("person.txt", "r") as fp: # Load the dictionary from the file person_dict = json.load(fp) # Print the contents of the dictionary print(person_dict)

Save the dictionary to a CSV file

The Python csv library provides functionality to read from and write to CSV files.

  • Use the csv.DictReader() method to read CSV files into a dictionary.
  • Use the csv.DictWriter() method to write a dictionary to a CSV file.

Example: Save the dictionary to a CSV file.

import csv # Dictionary to be saved person = print('Person dictionary') print(person) # Open a csv file for writing with open("person.csv", "w", newline="") as fp: # Create a writer object writer = csv.DictWriter(fp, fieldnames=person.keys()) # Write the header row writer.writeheader() # Write the data rows writer.writerow(person) print('Done writing dict to a csv file')
Person dictionary Done writing dict to a csv file

Person csv file

Example: Read a dictionary from a csv file

import csv # Open the csv file for reading with open("person.csv", "r") as infile: # Create a reader object reader = csv.DictReader(infile) # Iterate through the rows for row in reader: print(row)
OrderedDict([('name', 'Jessa'), ('country', 'USA'), ('telephone', '1178')])

Note: This will read the contents of the person.csv file and create a dictionary for each row in the file. You can then iterate through the rows and access the values in the dictionary using the column names as keys.

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

Write Dictionary to file Python (In 5 Ways)

How to write dictionary to file Python

In this article, we will be solving a problem statement for how to write dictionary to file python. We will be discussing the steps and python methods required to solve this problem.

What is Dictionary in Python?

Dictionary is one of the data types present in Python. Python dictionary is an unordered collection of items. It is dynamic and mutable in nature. Each item of a dictionary is a key-value pair.

We can define a dictionary by enclosing a list of key-value pairs in curly brackets < >. The keys present in the dictionary must be unique.

We can save dictionary to file in python in various ways. Below we have discussed some of the methods to write dictionary to file in python.

Method 1- Using json.dumps()

Python has an in-built package named as json to support JSON. The json package dumps() method is used to convert a Python object into a JSON string. To know about json package and method read here.

Steps to write dictionary in file using json.dumps:

  1. import json
  2. define the dictionary that you want to save in the file
  3. Open file in write mode
  4. Write dictionary using json.dumps()
  5. Close file

Python Code

# importing json library import json # defining the dictionary records = < "subject1" : 'python', "subject2" : 'java', "subject3" : 'ruby', "subject4" : 'c++', "subject5" : 'c' ># Open file in write mode file = open("mydict.txt", "w") # write dictionary into file using json.dumps() file.write(json.dumps(records)) file.close()

write dictionary to file output 1

mydict.txt file image given below:

Читайте также:  Что называется html страницами

Method 2- Using for loop and items()

The dictionary items() method returns an object which contains the list of key-value tuple pair.

  1. define dictionary
  2. Open file in write mode
  3. Loop on the items of the dictionary which we get from dictionary items() method
  4. Write the key and its corresponding value
  5. close the file

Using this method, you can write each key-value pair on the new line.

Python Code

# defining the dictionary records = < "subject1" : 'python', "subject2" : 'java', "subject3" : 'ruby', "subject4" : 'c++', "subject5" : 'c' ># Open file in write mode file = open("mydict.txt", "w") for key,value in records.items(): file.write(key + "t" + value + "n") file.close()

write dictionary to file output 2

mydict.txt file image given below:

Method 3- using str() to write dictionary to file Python

In this method, we just convert the dictionary into a string and write that string into the file. To convert a dictionary to a string we use the str() function.

Python Code

# defining the dictionary records = < "subject1" : 'python', "subject2" : 'java', "subject3" : 'ruby', "subject4" : 'c++', "subject5" : 'c' ># Open file in write mode file = open("mydict.txt", "w") # converting dictionary into string and writing into file file.write(str(records)) file.close()

write dictionary to file output 1

mydict.txt file image given below:

Method 4- using keys() method

By using the keys() method of the dictionary we will get all the keys. We will iterate over the keys and write the key and its corresponding value to the file.

Python code:

# defining the dictionary records = < "subject1" : 'python', "subject2" : 'java', "subject3" : 'ruby', "subject4" : 'c++', "subject5" : 'c' ># Open file in write binary mode file = open("mydict.txt", "w") # writing dictionary to file using keys() for key in records.keys(): file.write(key + "t" + recordsHow to write dict to file python + "n") file.close()

write dictionary to file output 2

mydict.txt file image given below:

Method 5- using pickle.dump() to write dictionary to file Python

The Python Pickle module is used for serializing and de-serializing a Python object. The pickle module converts python objects like lists, dictionaries, etc into a character stream. To know about the Python Pickle module click here.

Since the Pickle module stores data in serialized byte sequence, open the file in wb mode i.e write binary mode and use the pickle module’s dump() method to write dictionary into the file.

Python Code

#importing pickle module import pickle # defining the dictionary records = < "subject1" : 'python', "subject2" : 'java', "subject3" : 'ruby', "subject4" : 'c++', "subject5" : 'c' ># Open file in write binary mode file = open("mydict.txt", "wb") # writing dictionary to file using pickle.dump method pickle.dump(records, file) file.close()

Note!
When we use the pickle module to write to file, the data is in serialized binary format which is not readable. To read the data again from the file we can use pickle.load() which deserialize the file contents.

Conclusion

In this article, we have seen 5 different ways to write dictionary to file python. We can write dictionary to file by using json.dumps, for loop with dictionary items(), str(), keys() and pickle.dump() method.

I am Passionate Computer Engineer. Writing articles about programming problems and concepts allows me to follow my passion for programming and helping others.

Источник

Оцените статью