Programming Essentials Python - Overview of Collections - List of Tuples

Let us see an example of how we can read data from a file into list of tuples using Python as a programming language.

  • When we read data from a file into a list, typically each element in the list will be of type binary or string.
  • We can convert the element into a tuple to simplify the processing.
  • Once each element is converted to a tuple, we can access elements in the tuple using positional notation.
  • Let us see an example to read the data from a file into list of tuples and access dates.
ls -ltr /data/retail_db/orders/part-00000
tail /data/retail_db/orders/part-00000

Reading data from the file into a list:

path = '/data/retail_db/orders/part-00000'
orders_file = open(path)
orders_raw = orders_file.read()
orders = orders_raw.splitlines()

order = '1,2013-07-25 00:00:00.0,11599,CLOSED'
tuple(order.split(','))

order_tuples = [tuple(order.split(',')) for order in orders]
order_dates = [order[1] for order in order_tuples]

def get_order_details(order):
    order_details = order.split(',')
    return (int(order_details[0]), order_details[1], int(order_details[2]), order_details[3])
order_tuples = [get_order_details(order) for order in orders]
order_customer_ids = [order[2] for order in order_tuples]

path = '/data/retail_db/orders/part-00000'
orders_file = open(path)
orders_raw = orders_file.read()
orders = orders_raw.splitlines()
order_tuples = [(*order.split(','),) for order in orders] 
order_dates = [order[1] for order in order_tuples]
unique_dates = set(order_dates)

Key Concepts Explanation

Reading from File

This code snippet demonstrates how to read data from a file into a list and convert each element into a tuple.

Accessing Specific Data

The code illustrates how to access specific elements from the tuples once they are created from the file data.

Hands-On Tasks

  1. Read the data from a file into a list of tuples using Python.
  2. Extract specific details like order dates and customer IDs from the tuples.

Conclusion

In this article, we learned how to read data from a file into a list of tuples using Python and extract specific information from the tuples. It is essential to understand the conversion process from list to tuple for efficient data processing. Practice these concepts to enhance your Python programming skills and engage with the community for further learning opportunities.

Watch the video tutorial here