473,322 Members | 1,307 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

String formatting issue (dictionary)

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?
Nov 9 '20 #1
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.
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
Nov 10 '20 #2
SioSio
272 256MB
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))
Nov 10 '20 #3

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

Similar topics

5
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'
20
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 ' ...
5
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 ''.
0
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...
3
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...
3
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
7
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: ...
27
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 ?
11
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...
7
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
0
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...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
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...
0
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...
1
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)...
1
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...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
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
0
isladogs
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.