String formatting issue (dictionary)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • em9546
    New Member
    • Nov 2020
    • 1

    String formatting issue (dictionary)

    I have two separate txt files (reservations1, reservations2) that are set up like a reservation system for a restaurant.

    Each line in the file stands for a reservation and has the format: ```Name, Time, Status```. Status is either ```CONFIRMED``` or ```CANCELLED``` .

    I want to write a function ```show_reserva tions``` that takes as argument a string ```filename```, reads the file with the name ```filename``` and prints all ```CONFIRMED``` reservations in order of the time.

    This has to be part of the code:

    ```
    def show_reservatio ns(filename):

    *(write your code here)

    print("Reservat ions from first file:")
    print(show_rese rvations("reser vations1.txt"))
    print("Reservat ions from second file:")
    print(show_rese rvations("reser vations2.txt"))
    ```

    This is what I have done so far:

    ```
    def show_reservatio ns(filename):
    file = open(filename)
    confirmed = {}
    for line in file:
    info_parts = line.split(", ")
    if info_parts[2].strip() == "CONFIRMED" :
    confirmed[int(info_parts[1].strip())] = info_parts[0].strip()
    times = list(confirmed. keys())
    times.sort()
    sorted_confirme d = {}
    for time in times:
    sorted_confirme d[time] = confirmed[time]
    return sorted_confirme d

    print("Reservat ions from first file:")
    print(show_rese rvations("reser vations1.txt"))
    print("Reservat ions from second file:")
    print(show_rese rvations("reser vations2.txt"))
    ```

    The output is:

    ```
    Reservations from first file:
    {17: 'Asley', 18: 'Kira', 20: 'Jolyn'}
    Reservations from second file:
    {17: 'Codi', 18: 'Christel', 19: 'Valentine', 20: 'Eliseo'}
    ```

    It is close to what I want. But I want it to look like this:

    ```
    Reservations from first file:
    Asley, 17
    Kira, 18
    Jolyn, 20

    Reservations from second file:
    Codi, 17
    Christel, 18
    Valentine, 19
    Eliseo, 20
    ```

    I want to solve it without having to write the dictionary in the code.
    How do I correct it?
  • nabeelms
    New Member
    • Nov 2020
    • 1

    #2
    Firstly, since the file you have is a csv file, I would recommend using the built-in csv module in python to parse it as it will make it a lot easier.
    Code:
    import csv
    
    def show_reservation(file_path):
        # Using a list of tuples as I'm assuming we can have multiple reservations for the same time
        reservation_info = []
        # Use a context manager here so that you don't 
        # have to remember to close the file handle
        with open(file_path) as file_handle:
            # This assumes the the first line of the csv
            # is a row containing the headers (Name,Time,Status
            reader = csv.DictReader(file_handle, fieldnames=['Name', 'Time', 'Status'])
            for row in reader:
                if row['Status'].strip() == 'CONFIRMED':
                    reservation_info.append((row['Time'].strip(), row['Name'].strip()))
        # If the individual element of a list is a tuple, sorted will by default sort by comparing the first element, and if they're equal comparing the next element and so on. 
        # Time being a string here is perfectly fine for sorting and since it's the first element, will be given higher priority
        # We use the f-string and the generator expression in conjunction with join to generate the final output
        return '\n'.join(f'{i[0]}, {i[1]}' for i in sorted(reservation_info))
    https://docs.python.org/3.6/library/...csv.DictReader for the docs on csv.DictReader
    https://docs.python.org/3/tutorial/i...tring-literals for the docs on f-strings
    https://docs.python.org/3/reference/...or-expressions for the docs on generator expressions
    https://www.python.org/dev/peps/pep-0343/ -> PEP 343 on the with statement

    Comment

    • SioSio
      Contributor
      • Dec 2019
      • 272

      #3
      The #2's code is OK, but the output order is different from what the OP requires.
      line 18.
      Code:
          return '\n'.join(f'{i[1]}, {i[0]}' for i in sorted(reservation_info))

      Comment

      Working...