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 2836
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. -
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
The #2's code is OK, but the output order is different from what the OP requires.
line 18. - return '\n'.join(f'{i[1]}, {i[0]}' for i in sorted(reservation_info))
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Thomas Philips |
last post by:
Consider the following simple dictionary
e={1:'one', 2: 'two'}
e
>>>'one'
However, If I attempt to print e using a formatted string
print " %(1)s" %e,
I get a KeyError: '1'
|
by: Pierre Fortin |
last post by:
Hi!
"Python Essential Reference" - 2nd Ed, on P. 47 states that a string
format can include "*" for a field width (no restrictions noted); yet...
>>> "%*d" % (6,2) # works as expected
' ...
|
by: rodney.maxwell |
last post by:
Was doing some string formatting, noticed the following:
>>> x = None
>>> "%s" % x
'None'
Is there a reason it maps to 'None'? I had expected ''.
|
by: David Rifkind |
last post by:
I've seen some strange string formatting behavior on several XP and 2000
machines. I can get the same results with Graphics.DrawString, but the
easiest way to see it is to put a label on a VB or...
|
by: John Baker |
last post by:
Hi:
I have, I hope, a trivial formatting issue.
I have a field that I wish to format as 12.30 (00.00). IN other words two digits decimal
point and two digits. Using the format command (in a...
|
by: Franck |
last post by:
hello,
i'm looking for code (C# preferably)
in order to change programmatically in a datagrid
the string formatting expression of one bound colum
thank you
|
by: Steven D'Aprano |
last post by:
I have a sinking feeling I'm missing something really,
really simple.
I'm looking for a format string similar to '%.3f'
except that trailing zeroes are not included.
To give some examples:
...
|
by: fdu.xiaojf |
last post by:
Hi,
String formatting can be used to converting an integer to its octal or
hexadecimal form:
'307'
'c7'
But, can string formatting be used to convert an integer to its binary
form ?
|
by: Dustan |
last post by:
Is there any builtin function or module with a function similar to my
made-up, not-written deformat function as follows? I can't imagine it
would be too easy to write, but possible...
'I am...
|
by: sherifffruitfly |
last post by:
Hi,
God I hate datetime string formatting...
How do I get a string of the form "04-Oct-2006", for example, from a
DateTime object?
Thanks a jillion,
cdj
|
by: DolphinDB |
last post by:
Tired of spending countless mintues downsampling your data? Look no further!
In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: Vimpel783 |
last post by:
Hello!
Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
|
by: PapaRatzi |
last post by:
Hello,
I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
|
by: CloudSolutions |
last post by:
Introduction:
For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
|
by: Defcon1945 |
last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
|
by: af34tf |
last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome former...
| |