By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,553 Members | 851 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,553 IT Pros & Developers. It's quick & easy.

String formatting issue (dictionary)

P: 1
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_reservations``` 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_reservations(filename):

*(write your code here)

print("Reservations from first file:")
print(show_reservations("reservations1.txt"))
print("Reservations from second file:")
print(show_reservations("reservations2.txt"))
```

This is what I have done so far:

```
def show_reservations(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_confirmed = {}
for time in times:
sorted_confirmed[time] = confirmed[time]
return sorted_confirmed

print("Reservations from first file:")
print(show_reservations("reservations1.txt"))
print("Reservations from second file:")
print(show_reservations("reservations2.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?
2 Weeks Ago #1
Share this Question
Share on Google+
2 Replies

P: 1
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.
Expand|Select|Wrap|Line Numbers
  1. import csv
  2.  
  3. def show_reservation(file_path):
  4.     # Using a list of tuples as I'm assuming we can have multiple reservations for the same time
  5.     reservation_info = []
  6.     # Use a context manager here so that you don't 
  7.     # have to remember to close the file handle
  8.     with open(file_path) as file_handle:
  9.         # This assumes the the first line of the csv
  10.         # is a row containing the headers (Name,Time,Status
  11.         reader = csv.DictReader(file_handle, fieldnames=['Name', 'Time', 'Status'])
  12.         for row in reader:
  13.             if row['Status'].strip() == 'CONFIRMED':
  14.                 reservation_info.append((row['Time'].strip(), row['Name'].strip()))
  15.     # 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. 
  16.     # Time being a string here is perfectly fine for sorting and since it's the first element, will be given higher priority
  17.     # We use the f-string and the generator expression in conjunction with join to generate the final output
  18.     return '\n'.join(f'{i[0]}, {i[1]}' for i in sorted(reservation_info))
  19.  
  20.  
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
2 Weeks Ago #2

100+
P: 203
The #2's code is OK, but the output order is different from what the OP requires.
line 18.
Expand|Select|Wrap|Line Numbers
  1.     return '\n'.join(f'{i[1]}, {i[0]}' for i in sorted(reservation_info))
2 Weeks Ago #3

Post your reply

Sign in to post your reply or Sign up for a free account.