Save a dict to a file

Dictionary is a very famous object in python. And it is a collection of keys and values. The key of the dict must be immutable, and it can be integer, float, string, but neither a list nor a dict itself can be a key. So, sometimes we need to save the dict objects into a file. So we are going to see different methods to save a dict object in a file.

We can write the dictionary to a file in Python in different ways like:

  1. Comma-separated value file (.csv)
  2. Json file (.json)
  3. Text file (.txt)
  4. Pickle file (.pkl)

We are going to explain all the above methods.

Method 1: Save dictionary in CSV format

To save the dictionary into the CSV (Comma Separated Values), we use the CSV module. The comma-separated values to save the python dict is the most common and famous method. Most of the programmers use this method only to save the dict to a file. To save the dictionary in a file as CSV is very easy as we have to transfer the data as a string.

Example_1: dict_to_csv.py

# dict_to_csv.py
import csv

dict_sample = {'name': 'LinuxHint', 'city': 'CA', 'education': 'Engineering'}

with open('data.csv', 'w') as f:
    for key in dict_sample.keys():
        f.write("%s, %s\n" %(key, dict_sample[key]))

Line 2: We import the CSV python module.

Line 4: We created a sample dict data. We are going to try to save it in the form of a CSV file.

Line 6: We are using here ‘with’ statement to write the CSV file. The ‘with’ statement handles the exception handling automatically during the read or write of a file. We open the file data.csv in the write mode and assign that object to the variable f.

Line 7, We are running a for loop that extracts the key, and in the next line, it writes the key and the key_value to a CSV file. So this loop will run till there is data.

Output: data.csv

name, LinuxHint
city, CA
education, Engineering

So, the above shows the output file after writing on the data.csv.

Now, we understand how to save the dict to a file in the form of CSV. Let’s try with another example where we want to write a list of dict objects into the CSV file.

Example_2: dict_to_csv_2.py

# dict_to_csv_2.py

import csv

csvColumns = ['City', 'Country', 'Rank']
dictDemo = [
    {'City': 'New York', 'Country': 'USA', 'Rank': 3},
    {'City': 'Sydney', 'Country': 'Australia', 'Rank': 5},
    {'City': 'Dubai', 'Country': 'UAE', 'Rank': 10},
    {'City': 'Mumbai', 'Country': 'India', 'Rank': 17},
    {'City': 'Bejing', 'Country': 'China', 'Rank': 7},
]
csvFileName = "data.csv"
try:
    with open(csvFileName, 'w') as f:
        writer = csv.DictWriter(f, fieldnames=csvColumns)
        writer.writeheader()
        for data in dictDemo:
            writer.writerow(data)
except IOError:
    print("Got Error")

Line 3 to 12: We import the python CSV module and create a list of dict objects. We also created a list of column names.

Line 13: We assigned the CSV file name to a variable.

Line 15: We use the ‘with’ statement, and the statement assigned the __enter__ method return object to the f variable.

Line 16 to 19: After assigning the return object to the variable f, we called a DictWriter method of the CSV module and passed two parameters (filename (f) and column names). Then we call another method writeheader () which will write the first row of the CSV file, which is generally the name of the fields. Then we run a for loop on the list of the dict objects and write one by one to the CSV file using the writerow () method.

Method 2: Save the dict to a text file in JSON format (append mode)

We can also save the dict objects in the form of the JSON into a file. The below code will explain the same. This code also explains how we can add new JSON to an existing list of JSON.

Example: dict_to_file_asJSON.py

#dict_to_file_asJSON.py

import json

dictDemo = [
    {'City': 'New York', 'Country': 'USA', 'Rank': 3},
    {'City': 'Sydney', 'Country': 'Australia', 'Rank': 5},
    {'City': 'Dubai', 'Country': 'UAE', 'Rank': 10},
    {'City': 'Mumbai', 'Country': 'India', 'Rank': 17},
    {'City': 'Bejing', 'Country': 'China', 'Rank': 7},
]

filename = "dict.json"

# Writing the list of dict objects to a file
with open(filename, mode='w') as f:
    json.dump(dictDemo, f)

# Writing a new dict object to a file as append and overwrite the whole file
with open(filename, mode='w') as f:
    dictDemo.append({'City': 'Bejing', 'Country': 'China'})
    json.dump(dictDemo, f)

Output: dict.json

[{"City": "New York", "Country": "USA", "Rank": 3},
  {"City": "Sydney", "Country": "Australia", "Rank": 5},
  {"City": "Dubai", "Country": "UAE", "Rank": 10},
  {"City": "Mumbai", "Country": "India", "Rank": 17},
  {"City": "Bejing", "Country": "China", "Rank": 7},
  {"City": "Bejing", "Country": "China"}
]

Line 1 to 13: We import the JSON module. Then we create a list of dict objects for the demo. Then we assigned the name of the JSON file to a variable filename.

Line 15 to 17: We are using the ‘with’ statement to open the JSON file for writing, and then we use the json.dump method to convert the dict objects to JSON and then write into the file.

Line 20 to 22: These lines are very important because what will happen? If we try to add new JSON objects to the already written files. The previous data will be lost because of the overwriting. Then we can use the previous dict list name as we did (dictDemo), and then we append the new object into that. And at last, we convert the whole file into JSON and overwrite the whole file.

In the output, we can see that a new JSON object is added to an existing JSON list.

Method 3: Save the dictionary objects to a file in txt form

We can also save the dictionary into a normal string format into the file. So, the below method is a very simple way to save the dictionary objects into the file in the text form. But this code will not work if we want to append a new dictionary object to the file because it will overwrite on the previously written data. So, for that, we will see it in the next code.

Example: dict_to_txt.py

#dict_to_txt.py

dictDemo = [
    {'City': 'New York', 'Country': 'USA', 'Rank': 3},
    {'City': 'Sydney', 'Country': 'Australia', 'Rank': 5},
    {'City': 'Dubai', 'Country': 'UAE', 'Rank': 10},
    {'City': 'Mumbai', 'Country': 'India', 'Rank': 17},
    {'City': 'Bejing', 'Country': 'China', 'Rank': 7},
]

filename = "dict.txt"

# Writing the list of dict objects to a file
with open(filename, mode='w') as f:
    f.write(str(dictDemo))

Output: dict.txt

[{'City': 'New York', 'Country': 'USA', 'Rank': 3},
 {'City': 'Sydney', 'Country': 'Australia', 'Rank': 5},
  {'City': 'Dubai', 'Country': 'UAE', 'Rank': 10},
  {'City': 'Mumbai', 'Country': 'India', 'Rank': 17},
  {'City': 'Bejing', 'Country': 'China', 'Rank': 7}]

Line 1 to 11: We created a list of dictionary objects and assigned the name of the file “dict.txt” to a variable filename.

Line 14 to 15: We are using here ‘with’ statement, which automatically handles the exception. And we are writing the dict objects list as a string to a file.

Example: dict_to_txt_2.py

We have seen how to save the dict objects to a file in the .txt form. But in the above code, there is one problem with appending a new object. So, we change the append method from ‘w’ to ‘a’, which can solve our problem as shown below in the code.

#dict_to_txt_2.py

""":cvar
    This code will save the dict objects in the file with the
    append mode.
"""

dictDemo = [
    {'City': 'New York', 'Country': 'USA', 'Rank': 3},
    {'City': 'Sydney', 'Country': 'Australia', 'Rank': 5},
    {'City': 'Dubai', 'Country': 'UAE', 'Rank': 10},
    {'City': 'Mumbai', 'Country': 'India', 'Rank': 17},
    {'City': 'Bejing', 'Country': 'China', 'Rank': 7},
]

filename = "dict_to_file_appendMode.txt"

# Writing the list of dict objects to a file
with open(filename, mode='a') as f:
    f.write(str(dictDemo))

Line 7 to 15: We created a list of dictionary objects and assigned the name of the file “dict_to_file_appendMode.txt” to a variable filename.

Line 18 to 19: We change the mode = ‘a’, and this will solve our problem. The below output shows that we have added two dict objects in the same file without overwriting the previous data.

Output: dict_to_file_appendMode.txt

[{'City': 'New York', 'Country': 'USA', 'Rank': 3},
{'City': 'Sydney', 'Country': 'Australia', 'Rank': 5},
 {'City': 'Dubai', 'Country': 'UAE', 'Rank': 10},
 {'City': 'Mumbai', 'Country': 'India', 'Rank': 17},
 {'City': 'Bejing', 'Country': 'China', 'Rank': 7}]

 [{'City': 'New York', 'Country': 'USA', 'Rank': 3},
 {'City': 'Sydney', 'Country': 'Australia', 'Rank': 5},
 {'City': 'Dubai', 'Country': 'UAE', 'Rank': 10},
 {'City': 'Mumbai', 'Country': 'India', 'Rank': 17},
 {'City': 'Bejing', 'Country': 'China', 'Rank': 7}]

Method 4: Save the dict object to a file using the pickle method.

We can also save the dict object to a file using the python pickle module. The pickle module supports many objects for serialization in python and also supports dict objects.

# dict_to_file_use_pickle.py

import pickle

dictDemo = [
    {'City': 'New York', 'Country': 'USA', 'Rank': 3},
    {'City': 'Sydney', 'Country': 'Australia', 'Rank': 5},
    {'City': 'Dubai', 'Country': 'UAE', 'Rank': 10},
    {'City': 'Mumbai', 'Country': 'India', 'Rank': 17},
    {'City': 'Bejing', 'Country': 'China', 'Rank': 7},
]

filename = "picklefile.pkl"

with open(filename, 'ab') as f:
    pickle.dump(dictDemo,f)

Line 3 to 13: We import the module pickle and create a list of dict objects. We also create a filename where we will save our dict objects.

Line 15 to 16: We are using here ‘with’ statement and opening the file with appending mode and binary format. Then we dump the dict objects into the file.

Conclusion

So, we have seen different methods to save a dictionary object to a file. It depends upon the user that how they want to save the object into the file. The most common methods to save the dict object into the file are JSON and CSV. The JSON and CSV formats are very famous from the programming point of view or easy to handle in python. We have also seen the append mode of saving files.

The code for this article can be download from this link:

https://github.com/shekharpandey89/save-dict-object-to-a-file



from Linux Hint https://ift.tt/3Butq0h

Post a Comment

0 Comments