Why did adding 'Jane' with an age of 35 result in two entries ('name' and 'age') instead of one?

54 Views Asked by At

Here is a python code:

guests = {}
def read_guestlist(file_name):
  text_file = open(file_name,'r')
  while True:
    line_data = text_file.readline().strip().split(",")
    if len(line_data) < 2:
    # If no more lines, close file
      text_file.close()
      break
    name = line_data[0]
    age = int(line_data[1])
    guests.update({name:age})
    new_guest_info = yield name
    if new_guest_info and "age" in new_guest_info:
      new_guest_info["name"]=int(new_guest_info["age"])
      guests.update(new_guest_info)
      yield new_guest_info["name"]
  return guests

guest_generator=read_guestlist('guest_list.txt')
for guest in range(10):
  print(next(guest_generator))

new_guest_info={"name":"Jane", "age":35}
new_guest=guest_generator.send(new_guest_info)
print(new_guest)
for guest in guest_generator:
  print(guest)

def guests_above_21_generator(guests):
  for guest_name,guest_age in guests.items():
    if guest_age >= 21:
      yield guest_name

guests_above_21=guests_above_21_generator(guests)
for guest_name in guests_above_21:
  print("Yielding guest name:", guest_name)

I needed to add a guest onto the guests dictionally,-{"name":"Jane" , "age":35} However, the printout at the end shows what was added was two entries.- named "name" and "age"

1

There are 1 best solutions below

0
TheHungryCub On

When updating the guest dictionary with new guest information. In the line:

new_guest_info["name"]=int(new_guest_info["age"])

You’re updating the “name” key with the age, which is causing the duplication. It should be:

new_guest_info["age"]=int(new_guest_info["age"])