DEV Community

Cover image for Dictionaries and File Operations in Python
Scofield Idehen
Scofield Idehen

Posted on • Originally published at blog.learnhub.africa

Dictionaries and File Operations in Python

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.

What Are Dictionaries?

A Python dictionary consists of keys and values:

students = {"Sarah": 90, "Jerry": 75, "David": 82}

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

print(students["Sarah"]) # Prints 90

This syntax makes retrieving values easy. Plus, the lookup time is O(1), making access extremely fast, even at a large scale.

Why Dictionaries Are Powerful

There are several key reasons why dictionaries are so powerful in Python:

  • 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.
  • Intuitive syntax to add, modify, and access data. Use square brackets like my_dict[key] or the .get() method.
  • Built-in methods like .keys(), .values(), .items() to iterate through the data.
  • Ability to handle large amounts of data efficiently thanks to O(1) lookup time. Lists become slow with scale.
  • Ubiquity in Python code. Dictionaries are used everywhere, from data science to web development.

Use Cases Where Dictionaries Shine

Some examples of productivity-boosting use cases:

  • Storing user profiles in a social network app
  • Managing product inventory and availability for an ecommerce site
  • Caching frequently accessed data for fast lookups
  • Counting word frequencies in a large text corpus
  • Encoding/decoding data with lookup tables

In this hands-on walkthrough, we'll explore how to utilize these core structures together by following and explaining this code snippet:

Prerequisites

  • Python Installed.
  • Code editor, Vscode, Pycharm, or Atom.

You can find the entire code here and the txt file.

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)
Enter fullscreen mode Exit fullscreen mode

Dictionaries for User Credentials

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

a = {"jerry":1, "musa":2, "scofield":3}

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:

b = int(input("What is your password: "))

This will be the password we check against the dictionary.

Checking the Password

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

if b in a.values():

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:

else:
    print("Incorrect password!")
    print("Only these users can access:")
    for key in a.keys():
        print(key)
Enter fullscreen mode Exit fullscreen mode

Looping through .keys() prints out each registered user.

Handling File Operations

Next, we define a function to check if a file exists:

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

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:

if b in a.values():

    ws = input("Enter filename: ")

    print(new_file(was))
Enter fullscreen mode Exit fullscreen mode

This lets us validate if a file exists before trying to access it.

Why Dictionaries and Files Play Well Together

This example shows how dictionaries and file operations complement each other in Python:

  • Dictionaries provide fast lookup for validating credentials
  • Files give persistent storage for saving data between runs
  • Checking if a file exists avoids errors before reading/writing
  • The dictionary methods .values() and .keys() are used to access stored data

Together, they allow building programs like user registration systems, account dashboards, and other applications that require secure access and data storage.

Conclusion

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 Learnhub Blog; we write everything tech from Cloud computing to Frontend Dev, Cybersecurity, AI, and Blockchain.

Resource

Top comments (0)