Dictionaries and File Operations in Python
Tags: python, programming, beginners, tutorial
Published: 2023-10-01 12:53:50

<p data-pm-slice="1 3 []">Dictionaries are a core and versatile data structure in Python. Also known as hash tables in other languages, dictionaries allow storing data in key-value pairs that provide lightning-fast lookup times.</p>

<h4><strong>What Are Dictionaries?</strong></h4>
A Python dictionary consists of keys and values:

<code>students = {"Sarah": 90, "Jerry": 75, "David": 82}</code>

The student names are the keys, while the test scores are the values. You can access the values quickly by referring to the key:

<code>print(students["Sarah"]) # Prints 90</code>

This syntax makes retrieving values easy. Plus, the lookup time is O(1), making access extremely fast, even at a large scale.
<h4><strong>Why Dictionaries Are Powerful</strong></h4>
There are several key reasons why dictionaries are so powerful in Python:
<ul>
 	<li>Flexibility to store any object type as a value like strings, integers, lists, custom objects, etc. The key must be immutable, so typically a string or number.</li>
</ul>
<ul>
 	<li>Intuitive syntax to add, modify, and access data. Use square brackets like my_dict[key] or the .get() method.</li>
</ul>
<ul>
 	<li>Built-in methods like .keys(), .values(), .items() to iterate through the data.</li>
</ul>
<ul>
 	<li>Ability to handle large amounts of data efficiently thanks to O(1) lookup time. Lists become slow with scale.</li>
</ul>
<ul>
 	<li>Ubiquity in Python code. Dictionaries are used everywhere, from data science to web development.</li>
</ul>
<h4><strong>Use Cases Where Dictionaries Shine</strong></h4>
Some examples of productivity-boosting use cases:
<ul>
 	<li>Storing user profiles in a social network app</li>
 	<li>Managing product inventory and availability for an ecommerce site</li>
 	<li>Caching frequently accessed data for fast lookups</li>
 	<li>Counting word frequencies in a large text corpus</li>
 	<li>Encoding/decoding data with lookup tables</li>
</ul>
In this hands-on walkthrough, we'll explore how to utilize these core structures together by following and explaining this code snippet:
<h4>Prerequisites</h4>
<ul>
 	<li>Python Installed.</li>
 	<li>Code editor, Vscode, Pycharm, or Atom.</li>
</ul>
You can find the entire <a class="attrlink" href="https://github.com/Scofield-Idehen/python_code_file" target="_blank" rel="noopener noreferrer nofollow">code here</a> and the txt file.
```python
a = {"jerry":1, "musa":2, "scofield":3}
b = int(input("What is your password: "))


def new_file(f):
    if f in open('exampl45.txt').read().split():
        return "File exists"
    else:
        return "File not found"

if b in a.values():
    ws = input("Enter filename: ")
    print(new_file(ws))
else:
    print("Incorrect password!")
    print("Only these users can access:")
    for key in a.keys():
        print(key)
```
<strong>Dictionaries for User Credentials</strong>

The first line creates a dictionary a to store usernames as keys and passwords as values:

<code>a = {"jerry":1, "musa":2, "scofield":3}</code>

This acts as a simple database of registered users. Dictionaries provide fast lookup time, making them perfect for storing user credentials.

Next, we get keyboard input and convert it to an integer:

<code>b = int(input("What is your password: "))</code>

This will be the password we check against the dictionary.

<strong>Checking the Password</strong>

To verify the password, we check if it exists in the dictionary values:

<code>if b in a.values():</code>

The .values() method returns a list of all values in the dictionary. So this checks if the inputted password matches any stored values.

If correct, we move on. If not, we print an error and show the valid usernames:
```python
else:
    print("Incorrect password!")
    print("Only these users can access:")
    for key in a.keys():
        print(key)
```
Looping through .keys() prints out each registered user.

<strong>Handling File Operations</strong>

Next, we define a function to check if a file exists:
```python
def new_file(f):
    if f in open('exampl45.txt').read().split():
        return "File exists"
    else: 
        return "File not found"
```
Opening the file, reading the contents, and splitting into a list lets us check if the filename f exists. We return a string indicating if it was found or not.

If the password was correct, we call this function:
```python
if b in a.values():

    ws = input("Enter filename: ")

    print(new_file(was))
```
This lets us validate if a file exists before trying to access it.

<strong>Why Dictionaries and Files Play Well Together</strong>

This example shows how dictionaries and file operations complement each other in Python:
<ul>
 	<li>Dictionaries provide fast lookup for validating credentials</li>
 	<li>Files give persistent storage for saving data between runs</li>
 	<li>Checking if a file exists avoids errors before reading/writing</li>
 	<li>The dictionary methods .values() and .keys() are used to access stored data</li>
</ul>
Together, they allow building programs like user registration systems, account dashboards, and other applications that require secure access and data storage.
<h4>Conclusion</h4>
In this hands-on walkthrough, we saw how Python dictionaries and file operations can work together by following this code snippet above.

Dictionaries provided user credential validation, while file functions gave persistent storage capabilities. Together, they enabled the building of a simple user access program.

Mastering Python's dictionaries and file operations unlocks the ability to develop robust applications across many domains. These core structures provide the data backbone for many powerful Python programs.

I hope you enjoyed reading this guide and feel motivated to start your Python programming journey.

If you find this post exciting, find more exciting posts on <a class="attrlink" href="http://blog.learnhub.africa/" target="_blank" rel="noopener noreferrer nofollow">Learnhub Blog</a>; we write everything tech from <a class="attrlink" href="https://blog.learnhub.africa/category/cloud-computing/" target="_blank" rel="noopener noreferrer nofollow">Cloud computing</a> to <a class="attrlink" href="https://blog.learnhub.africa/category/frontend/" target="_blank" rel="noopener noreferrer nofollow">Frontend Dev</a>, <a class="attrlink" href="https://blog.learnhub.africa/category/security/" target="_blank" rel="noopener noreferrer nofollow">Cybersecurity</a>, <a class="attrlink" href="https://blog.learnhub.africa/category/data-science/" target="_blank" rel="noopener noreferrer nofollow">AI</a>, and <a class="attrlink" href="https://blog.learnhub.africa/category/blockchain/" target="_blank" rel="noopener noreferrer nofollow">Blockchain</a>.
<h4>Resource</h4>
<ul>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/05/26/20-essential-python-extensions-for-visual-studio-code/" target="_blank" rel="noopener noreferrer nofollow">20 Essential Python Extensions for Visual Studio Code</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/04/27/using-python-for-web-scraping-and-data-extraction/" target="_blank" rel="noopener noreferrer nofollow">Using Python for Web Scraping and Data Extraction</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/06/06/13-powerful-python-snippets-to-automate-tasks/" target="_blank" rel="noopener noreferrer nofollow">13 Powerful Python Snippets To Automate Tasks</a></li>
 	<li><a class="attrlink" href="https://www.python.org/about/gettingstarted/" target="_blank" rel="noopener noreferrer nofollow">Getting Started with Python</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/09/09/python-for-the-seniors-part-2/" target="_blank" rel="noopener noreferrer nofollow">Python for Seniors</a></li>
</ul>