Named tuples

  1. namedtuples_sales.py, below, will create a restaurant receipt, indicating the store ID, sales date, amount, and number of guests:
    • The line 9 shows the creation of the named tuple. The first argument to the named tuple is the name of the tuple subclass. The remaining arguments are the fields for the tuple.
    • The lines 10 and 11 create two different restaurants, showing receipts for the same day.
    • The line 12 and line 13 show how to access the individual fields within the different tuples using the field names rather than the indexes.
    • The line 14 shows that these restaurant instances are, indeed, actual tuples. They can be iterated over like regular sequences, using an integer to identify each field's index.
  1. One usual way to create named tuples without having to create each one individually is to simply convert an iterable object to a namedtuple using _make. The input iterable can be a list, tuple, or dictionary. In receipts_make.py, we take a list, with values that meet the requirements for the namedtuple fields, and convert it directly to a named tuple:
      In [18]: my_list = [27, "11-13-2017", 84.98, 5]
In [19]: store27 = salesReceipt._make(my_list)
In [20]: print(store27)
salesReceipt(storeID=27, saleDate='11-13-2017', saleAmount=84.98, totalGuests=5)
    • The line 18 creates the list used for the conversion.
    • The line 19 uses the _make method to convert the list to a namedtuple object.
    • The line 20 prints out the new namedtuple instance, showing that the data in the converted namedtuple is no different than making the namedtuple manually.
  1. If you just want to see what the field names are in a named tuple object, you can use the _fields identifier:
      In [21]: print(store15._fields)
('storeID', 'saleDate', 'saleAmount', 'totalGuests')
  1. The final example shows how named tuples can be used when working with CSV files, allowing data access via names rather than indexes. This way, the data is easier to work with, as there is meaning ascribed to each field, rather than trying to figure out which index value applies to the desired field.

Of course, you have to have a CSV file available to use this example. sales_csv.py shows that the structure is easy, as all you have to have are four entries per line, signifying the store ID, the sales date, the sales amount, and the total number of guests:

      In [22]: from csv import reader
 
      In [23]: with open("sales_record.csv", "r") as input_file:
      ...:     csv_fields = reader(input_file)
      ...:     for field_list in csv_fields:
      ...:         store_record = salesReceipt._make(field_list)
      ...:         total_sales += float(store_record.saleAmount)
      ...:         

      In [24]: print("Total sales = ", total_sales)
      Total sales =  105.97
    • In line 22, we import the reader method from the csv module.
    • The line 23 shows one way to import the CSV file. The traditional with open... methodology is used to ensure that the file is automatically closed when it is no longer being used.

Each field in the CSV file is read into a variable, which is then iterated over. The CSV fields are converted to a named tuple via the _make method.

Finally, the total amount of sales for all the entries in the CSV file are summed and put into a variable. Note that the values are cast to a float prior to being summed, to ensure no errors are generated due to mismatching types.

    • In line 24, the total sales are printed out, showing that the records in the CSV file were properly retrieved and converted.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset