06-15-2022, 03:15 AM
How to Save a Dictionary to a File in Python
<div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{"align":"left","id":"415307","slug":"default","valign":"top","reference":"auto","count":"0","readonly":"","score":"0","best":"5","gap":"5","greet":"Rate this post","legend":"0\/5 - (0 votes)","size":"24","width":"0","_legend":"{score}\/{best} - ({count} {votes})"}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 0px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend"> <span class="kksr-muted">Rate this post</span> </div>
</div>
<p class="has-global-color-8-background-color has-background"><strong>Summary: </strong>You can use Python’s <code>pickle</code> library to save dictionary data to a file. Another efficient approach to save dictionary data to a file is to use Python’s built-in <code>JSON</code> package. You can also use simple file handling functions to store dictionary data in a text file directly.</p>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<p><strong>Problem: </strong>Given a Python dictionary. How will you save the data from the dictionary to a file so that it can be loaded to be used later?</p>
<p>You might need the help of persistent storage systems like databases or files to store serialized data structures like <a rel="noreferrer noopener" href="https://blog.finxter.com/declare-an-array-python/" target="_blank">arrays</a>, <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" target="_blank">lists</a>, and <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" target="_blank">dictionaries</a>. One of the major reasons behind doing so is databases and files are reusable, i.e., after analyzing the given data, we can store it in the file, and later that data can be read to use in an application. </p>
<p>This article will deal with dictionary data that you can store in a file.</p>
<p><strong>Example:</strong> Consider the following <strong><a href="https://blog.finxter.com/python-dictionary/" target="_blank" rel="noreferrer noopener">dictionary</a></strong>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">d = {'country': 'Germany', 'capital': 'Berlin'}</pre>
<p><strong>Challenge:</strong> How will you store the key-value pairs of the above dictionary in a file?</p>
<p><strong>Related Tutorials: </strong></p>
<ul class="has-base-2-background-color has-background">
<li><strong><a rel="noreferrer noopener" href="https://blog.finxter.com/writing-a-list-to-a-file-in-python/" target="_blank">Writing a List to a File in Python</a></strong></li>
<li><strong><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-read-a-dictionary-from-a-file/" target="_blank">How to Read a Dictionary from a File</a></strong></li>
<li><strong><a rel="noreferrer noopener" href="https://blog.finxter.com/correct-way-to-write-line-to-file-in-python/" target="_blank">Correct Way to Write line To File in Python</a></strong></li>
</ul>
<p>There are numerous ways to store dictionary data in a file using Python. Let’s have a look at some of them:</p>
<h2><strong>Method 1:</strong> Using <a rel="noreferrer noopener" href="https://docs.python.org/3/library/pickle.html" target="_blank">Pickle</a></h2>
<ul>
<li>Pickle is a module in Python that uses binary protocols to serialize and de-serialize an object structure. “<em>Pickling</em>” refers to the process of converting a Python object to a byte stream. “<em>Unpickling</em>” is just the reverse operation wherein a byte stream is converted to a Python object. Pickling is also sometimes referred to as serialization. </li>
<li>A good idea to implement a Pickle file is when you are dealing with sensitive data or when you need to keep a program status across sessions.</li>
</ul>
<p><strong>Approach: </strong></p>
<ul class="has-global-color-8-background-color has-background">
<li>Create the pickle file (i.e., filename.pkl) with the help of the <code>open(filename, mode)</code> function. Since we will be storing the data in a pickle file which stores the data as a binary stream, hence, open the file in binary (“<code data-enlighter-language="generic" class="EnlighterJSRAW">wb</code>“) mode. </li>
<li>Use the <code>pickle.dump(dictionary, filename)</code> method to store/serialize the dictionary data to the file. </li>
<li>To read data from this file, call the <code>pickle.load(filename)</code> method. </li>
<li><strong>Note: </strong>Remember to close the file.</li>
</ul>
<p><strong>Code:</strong> Let’s visualize the above approach with the help of the following code snippet:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pickle
d = {'country': 'Germany', 'capital': 'Berlin'}
file = open("dictionary_data.pkl", "wb")
pickle.dump(d, file)
file.close()
file = open("dictionary_data.pkl", "rb")
output = pickle.load(file)
print(output)
file.close()</pre>
<p><strong>Output:</strong></p>
<figure class="wp-block-image size-full is-style-default"><img loading="lazy" width="478" height="255" src="https://blog.finxter.com/wp-content/uploads/2022/06/image-82.png" alt="" class="wp-image-417194" srcset="https://blog.finxter.com/wp-content/uploads/2022/06/image-82.png 478w, https://blog.finxter.com/wp-content/uplo...00x160.png 300w" sizes="(max-width: 478px) 100vw, 478px" /></figure>
<p>Output Console:</p>
<pre class="wp-block-code"><code>{'country': 'Germany', 'capital': 'Berlin'}</code></pre>
<h2><strong>Method 2:</strong> Using json</h2>
<p><strong>Approach: </strong></p>
<ul class="has-global-color-8-background-color has-background">
<li>Open the file in write mode by calling <code>open('filename','mode')</code>.</li>
<li>Use the <code>json.dump(dictionary, filename)</code> function to convert the dictionary data to the json format and write it to the file. </li>
<li>To read the data from this file, read the data from it by calling the <code>file.read()</code> function.</li>
<li><strong>Note: </strong>Remember to close the file.</li>
</ul>
<p><strong>Code: </strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import json
d = {'country': 'Germany', 'capital': 'Berlin'}
file = open("dictionary_data.json", "w")
json.dump(d, file)
file.close()
file = open("dictionary_data.json", "r")
output = file.read()
print(output)
file.close()</pre>
<p><strong>Output:</strong></p>
<figure class="wp-block-image size-full is-style-default"><img loading="lazy" width="478" height="255" src="https://blog.finxter.com/wp-content/uploads/2022/06/image-83.png" alt="" class="wp-image-417332" srcset="https://blog.finxter.com/wp-content/uploads/2022/06/image-83.png 478w, https://blog.finxter.com/wp-content/uplo...00x160.png 300w" sizes="(max-width: 478px) 100vw, 478px" /></figure>
<p>Output Console:</p>
<pre class="wp-block-code"><code>{"country": "Germany", "capital": "Berlin"}</code></pre>
<p><strong>Note: </strong>The <code>json.dump()</code> method is used to convert a Python object to a JSON string.</p>
<h2><strong>Method 3:</strong> Using Numpy</h2>
<p>Using JSON and Pickle are the best options when it comes to storing a dictionary to a file. But we also have another way of doing so using the Numpy module. </p>
<p class="has-global-color-8-background-color has-background"><strong>Approach: </strong>Call the <code>np.save(filename, dictionary)</code> function to save the file into the disk. To read the data from this file us call the <code>np.load('file.npy', allow_pickle='TRUE').item()</code> function.</p>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
d = {'country': 'Germany', 'capital': 'Berlin'}
np.save('file.npy', d)
read_d = np.load('file.npy', allow_pickle='TRUE').item()
print(read_d)</pre>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<p class="has-base-background-color has-background"><strong>Read Here: <a href="https://blog.finxter.com/numpy-tutorial/" target="_blank" rel="noreferrer noopener">NumPy Tutorial – Everything You Need to Know to Get Started</a></strong></p>
<p><strong>Do you want to become a NumPy master?</strong> Check out our interactive puzzle book <a href="https://amzn.to/39dEykm" target="_blank" rel="noreferrer noopener" title="https://amzn.to/39dEykm"><strong>Coffee Break NumPy</strong></a> and boost your data science skills! <em>(Amazon link opens in new tab.)</em></p>
<div class="wp-block-image">
<figure class="aligncenter size-medium"><a href="https://amzn.to/39dEykm" target="_blank" rel="noopener noreferrer"><img loading="lazy" width="200" height="300" src="https://blog.finxter.com/wp-content/uploads/2019/04/Cover_Coffee_Break_NumPy-200x300.jpg" alt="Coffee Break NumPy" class="wp-image-2766"/></a></figure>
</div>
<h2>Method 4: Basic Approach</h2>
<p>Last but not the least, you can store the dictionary data to a simple text file by simply writing the data to the file using file handling functions.</p>
<p><strong>Approach:</strong></p>
<ul class="has-global-color-8-background-color has-background">
<li>Call the <code>open('filename.txt', 'w')</code> function to create/open the file in the write mode.</li>
<li>Use the <code>file.write(str(dictionary))</code> function to write the dictionary data to the file and then close the file.</li>
<li>To read the data from this file open up the file and use the <code>file.read()</code> method to read the data from this file.</li>
</ul>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">d = {'country': 'Germany', 'capital': 'Berlin'}
f = open('file.txt', 'w')
f.write(str(d))
f.close()
f = open('file.txt', 'r')
data = f.read()
print(data)
f.close()</pre>
<p><strong>Output:</strong></p>
<figure class="wp-block-image size-full is-style-default"><img loading="lazy" width="491" height="263" src="https://blog.finxter.com/wp-content/uploads/2022/06/image-84.png" alt="" class="wp-image-417367" srcset="https://blog.finxter.com/wp-content/uploads/2022/06/image-84.png 491w, https://blog.finxter.com/wp-content/uplo...00x161.png 300w" sizes="(max-width: 491px) 100vw, 491px" /></figure>
<p><strong>Recommended Reads on File Handling:</strong></p>
<ul class="has-base-background-color has-background">
<li><strong><a href="https://blog.finxter.com/correct-way-to-write-line-to-file-in-python/" target="_blank" rel="noreferrer noopener">Correct Way to Write line To File in Python</a></strong></li>
<li><strong><a href="https://blog.finxter.com/how-to-modify-a-text-file-in-python/" target="_blank" rel="noreferrer noopener">How to Modify a Text File in Python?</a></strong></li>
</ul>
<h2>Conclusion</h2>
<p>We learned four ways of storing the dictionary data to a file in Python in this article. The most suitable ways of storing the dictionary data in a file are using the JSON or the pickle modules. However, feel free to try out the other ways discussed in this tutorial. </p>
<p>I hope this article helped you. Please <strong><a href="https://blog.finxter.com/subscribe/" target="_blank" rel="noreferrer noopener">subscribe</a></strong> and <strong><a href="https://blog.finxter.com/" target="_blank" rel="noreferrer noopener">stay tuned</a></strong> for more interesting tutorials and discussions.</p>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<p><strong>But before we move on, I’m excited to present you my new Python book <a rel="noreferrer noopener" href="https://amzn.to/2WAYeJE" target="_blank" title="https://amzn.to/2WAYeJE">Python One-Liners</a></strong> (Amazon Link).</p>
<p>If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a <strong>single line of Python code.</strong> But it’s also an <strong>introduction to computer science</strong>, data science, machine learning, and algorithms. <strong><em>The universe in a single line of Python!</em></strong></p>
<div class="wp-block-image">
<figure class="aligncenter"><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noopener noreferrer"><img loading="lazy" width="215" height="283" src="https://blog.finxter.com/wp-content/uploads/2020/02/image-1.png" alt="" class="wp-image-5969"/></a></figure>
</div>
<p>The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco). </p>
<p>Link: <a href="https://nostarch.com/pythononeliners" target="_blank" rel="noreferrer noopener">https://nostarch.com/pythononeliners</a></p>
</div>
https://www.sickgaming.net/blog/2022/06/...in-python/
<div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{"align":"left","id":"415307","slug":"default","valign":"top","reference":"auto","count":"0","readonly":"","score":"0","best":"5","gap":"5","greet":"Rate this post","legend":"0\/5 - (0 votes)","size":"24","width":"0","_legend":"{score}\/{best} - ({count} {votes})"}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 0px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend"> <span class="kksr-muted">Rate this post</span> </div>
</div>
<p class="has-global-color-8-background-color has-background"><strong>Summary: </strong>You can use Python’s <code>pickle</code> library to save dictionary data to a file. Another efficient approach to save dictionary data to a file is to use Python’s built-in <code>JSON</code> package. You can also use simple file handling functions to store dictionary data in a text file directly.</p>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<p><strong>Problem: </strong>Given a Python dictionary. How will you save the data from the dictionary to a file so that it can be loaded to be used later?</p>
<p>You might need the help of persistent storage systems like databases or files to store serialized data structures like <a rel="noreferrer noopener" href="https://blog.finxter.com/declare-an-array-python/" target="_blank">arrays</a>, <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" target="_blank">lists</a>, and <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" target="_blank">dictionaries</a>. One of the major reasons behind doing so is databases and files are reusable, i.e., after analyzing the given data, we can store it in the file, and later that data can be read to use in an application. </p>
<p>This article will deal with dictionary data that you can store in a file.</p>
<p><strong>Example:</strong> Consider the following <strong><a href="https://blog.finxter.com/python-dictionary/" target="_blank" rel="noreferrer noopener">dictionary</a></strong>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">d = {'country': 'Germany', 'capital': 'Berlin'}</pre>
<p><strong>Challenge:</strong> How will you store the key-value pairs of the above dictionary in a file?</p>
<p><strong>Related Tutorials: </strong></p>
<ul class="has-base-2-background-color has-background">
<li><strong><a rel="noreferrer noopener" href="https://blog.finxter.com/writing-a-list-to-a-file-in-python/" target="_blank">Writing a List to a File in Python</a></strong></li>
<li><strong><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-read-a-dictionary-from-a-file/" target="_blank">How to Read a Dictionary from a File</a></strong></li>
<li><strong><a rel="noreferrer noopener" href="https://blog.finxter.com/correct-way-to-write-line-to-file-in-python/" target="_blank">Correct Way to Write line To File in Python</a></strong></li>
</ul>
<p>There are numerous ways to store dictionary data in a file using Python. Let’s have a look at some of them:</p>
<h2><strong>Method 1:</strong> Using <a rel="noreferrer noopener" href="https://docs.python.org/3/library/pickle.html" target="_blank">Pickle</a></h2>
<ul>
<li>Pickle is a module in Python that uses binary protocols to serialize and de-serialize an object structure. “<em>Pickling</em>” refers to the process of converting a Python object to a byte stream. “<em>Unpickling</em>” is just the reverse operation wherein a byte stream is converted to a Python object. Pickling is also sometimes referred to as serialization. </li>
<li>A good idea to implement a Pickle file is when you are dealing with sensitive data or when you need to keep a program status across sessions.</li>
</ul>
<p><strong>Approach: </strong></p>
<ul class="has-global-color-8-background-color has-background">
<li>Create the pickle file (i.e., filename.pkl) with the help of the <code>open(filename, mode)</code> function. Since we will be storing the data in a pickle file which stores the data as a binary stream, hence, open the file in binary (“<code data-enlighter-language="generic" class="EnlighterJSRAW">wb</code>“) mode. </li>
<li>Use the <code>pickle.dump(dictionary, filename)</code> method to store/serialize the dictionary data to the file. </li>
<li>To read data from this file, call the <code>pickle.load(filename)</code> method. </li>
<li><strong>Note: </strong>Remember to close the file.</li>
</ul>
<p><strong>Code:</strong> Let’s visualize the above approach with the help of the following code snippet:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pickle
d = {'country': 'Germany', 'capital': 'Berlin'}
file = open("dictionary_data.pkl", "wb")
pickle.dump(d, file)
file.close()
file = open("dictionary_data.pkl", "rb")
output = pickle.load(file)
print(output)
file.close()</pre>
<p><strong>Output:</strong></p>
<figure class="wp-block-image size-full is-style-default"><img loading="lazy" width="478" height="255" src="https://blog.finxter.com/wp-content/uploads/2022/06/image-82.png" alt="" class="wp-image-417194" srcset="https://blog.finxter.com/wp-content/uploads/2022/06/image-82.png 478w, https://blog.finxter.com/wp-content/uplo...00x160.png 300w" sizes="(max-width: 478px) 100vw, 478px" /></figure>
<p>Output Console:</p>
<pre class="wp-block-code"><code>{'country': 'Germany', 'capital': 'Berlin'}</code></pre>
<h2><strong>Method 2:</strong> Using json</h2>
<p><strong>Approach: </strong></p>
<ul class="has-global-color-8-background-color has-background">
<li>Open the file in write mode by calling <code>open('filename','mode')</code>.</li>
<li>Use the <code>json.dump(dictionary, filename)</code> function to convert the dictionary data to the json format and write it to the file. </li>
<li>To read the data from this file, read the data from it by calling the <code>file.read()</code> function.</li>
<li><strong>Note: </strong>Remember to close the file.</li>
</ul>
<p><strong>Code: </strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import json
d = {'country': 'Germany', 'capital': 'Berlin'}
file = open("dictionary_data.json", "w")
json.dump(d, file)
file.close()
file = open("dictionary_data.json", "r")
output = file.read()
print(output)
file.close()</pre>
<p><strong>Output:</strong></p>
<figure class="wp-block-image size-full is-style-default"><img loading="lazy" width="478" height="255" src="https://blog.finxter.com/wp-content/uploads/2022/06/image-83.png" alt="" class="wp-image-417332" srcset="https://blog.finxter.com/wp-content/uploads/2022/06/image-83.png 478w, https://blog.finxter.com/wp-content/uplo...00x160.png 300w" sizes="(max-width: 478px) 100vw, 478px" /></figure>
<p>Output Console:</p>
<pre class="wp-block-code"><code>{"country": "Germany", "capital": "Berlin"}</code></pre>
<p><strong>Note: </strong>The <code>json.dump()</code> method is used to convert a Python object to a JSON string.</p>
<h2><strong>Method 3:</strong> Using Numpy</h2>
<p>Using JSON and Pickle are the best options when it comes to storing a dictionary to a file. But we also have another way of doing so using the Numpy module. </p>
<p class="has-global-color-8-background-color has-background"><strong>Approach: </strong>Call the <code>np.save(filename, dictionary)</code> function to save the file into the disk. To read the data from this file us call the <code>np.load('file.npy', allow_pickle='TRUE').item()</code> function.</p>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
d = {'country': 'Germany', 'capital': 'Berlin'}
np.save('file.npy', d)
read_d = np.load('file.npy', allow_pickle='TRUE').item()
print(read_d)</pre>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<p class="has-base-background-color has-background"><strong>Read Here: <a href="https://blog.finxter.com/numpy-tutorial/" target="_blank" rel="noreferrer noopener">NumPy Tutorial – Everything You Need to Know to Get Started</a></strong></p>
<p><strong>Do you want to become a NumPy master?</strong> Check out our interactive puzzle book <a href="https://amzn.to/39dEykm" target="_blank" rel="noreferrer noopener" title="https://amzn.to/39dEykm"><strong>Coffee Break NumPy</strong></a> and boost your data science skills! <em>(Amazon link opens in new tab.)</em></p>
<div class="wp-block-image">
<figure class="aligncenter size-medium"><a href="https://amzn.to/39dEykm" target="_blank" rel="noopener noreferrer"><img loading="lazy" width="200" height="300" src="https://blog.finxter.com/wp-content/uploads/2019/04/Cover_Coffee_Break_NumPy-200x300.jpg" alt="Coffee Break NumPy" class="wp-image-2766"/></a></figure>
</div>
<h2>Method 4: Basic Approach</h2>
<p>Last but not the least, you can store the dictionary data to a simple text file by simply writing the data to the file using file handling functions.</p>
<p><strong>Approach:</strong></p>
<ul class="has-global-color-8-background-color has-background">
<li>Call the <code>open('filename.txt', 'w')</code> function to create/open the file in the write mode.</li>
<li>Use the <code>file.write(str(dictionary))</code> function to write the dictionary data to the file and then close the file.</li>
<li>To read the data from this file open up the file and use the <code>file.read()</code> method to read the data from this file.</li>
</ul>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">d = {'country': 'Germany', 'capital': 'Berlin'}
f = open('file.txt', 'w')
f.write(str(d))
f.close()
f = open('file.txt', 'r')
data = f.read()
print(data)
f.close()</pre>
<p><strong>Output:</strong></p>
<figure class="wp-block-image size-full is-style-default"><img loading="lazy" width="491" height="263" src="https://blog.finxter.com/wp-content/uploads/2022/06/image-84.png" alt="" class="wp-image-417367" srcset="https://blog.finxter.com/wp-content/uploads/2022/06/image-84.png 491w, https://blog.finxter.com/wp-content/uplo...00x161.png 300w" sizes="(max-width: 491px) 100vw, 491px" /></figure>
<p><strong>Recommended Reads on File Handling:</strong></p>
<ul class="has-base-background-color has-background">
<li><strong><a href="https://blog.finxter.com/correct-way-to-write-line-to-file-in-python/" target="_blank" rel="noreferrer noopener">Correct Way to Write line To File in Python</a></strong></li>
<li><strong><a href="https://blog.finxter.com/how-to-modify-a-text-file-in-python/" target="_blank" rel="noreferrer noopener">How to Modify a Text File in Python?</a></strong></li>
</ul>
<h2>Conclusion</h2>
<p>We learned four ways of storing the dictionary data to a file in Python in this article. The most suitable ways of storing the dictionary data in a file are using the JSON or the pickle modules. However, feel free to try out the other ways discussed in this tutorial. </p>
<p>I hope this article helped you. Please <strong><a href="https://blog.finxter.com/subscribe/" target="_blank" rel="noreferrer noopener">subscribe</a></strong> and <strong><a href="https://blog.finxter.com/" target="_blank" rel="noreferrer noopener">stay tuned</a></strong> for more interesting tutorials and discussions.</p>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<p><strong>But before we move on, I’m excited to present you my new Python book <a rel="noreferrer noopener" href="https://amzn.to/2WAYeJE" target="_blank" title="https://amzn.to/2WAYeJE">Python One-Liners</a></strong> (Amazon Link).</p>
<p>If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a <strong>single line of Python code.</strong> But it’s also an <strong>introduction to computer science</strong>, data science, machine learning, and algorithms. <strong><em>The universe in a single line of Python!</em></strong></p>
<div class="wp-block-image">
<figure class="aligncenter"><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noopener noreferrer"><img loading="lazy" width="215" height="283" src="https://blog.finxter.com/wp-content/uploads/2020/02/image-1.png" alt="" class="wp-image-5969"/></a></figure>
</div>
<p>The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco). </p>
<p>Link: <a href="https://nostarch.com/pythononeliners" target="_blank" rel="noreferrer noopener">https://nostarch.com/pythononeliners</a></p>
</div>
https://www.sickgaming.net/blog/2022/06/...in-python/