How do I make my first if statement true when a device object is equal to 1?
For example, "Lebron" key has one value and it is is "pc" therefore it should print "Lebron's favourite item is pc". But this is not working. instead, my elif statement returns as true instead for all the items in the persons dictionary. I believe my all len()
function calls result in more than one.
persons = {"Rondo": ["computer, pc, phone, ps5, ps4"],
"Lebron": ["pc"],
"Kobe": ["cellphone"],
"Ronel": ["Laptop, Phone"]
}
for person, devices in persons.items():
for device in devices:
if len(device) == 1:
print(f"{person}'s favorite item is: {device}")
elif len(device) > 1:
print(f"{person}'s favorite items are:")
for device in devices:
print(device)
CodePudding user response:
It seems like your device lists are length-1 lists with a ", "
separated string. You could do something like
for person, devices in persons.items():
device_list = devices[0].split(", ")
if len(device_list) == 1:
print(f"{person}'s favorite item is: {device_list[0]}")
elif len(device_list) > 1:
print(f"{person}'s favorite items are:")
for device in device_list:
print(device)
CodePudding user response:
You don't need the second for loop as you can check the length of devices directly.
Also, your device array is always an array of size 1, so you have to split the items based on whitespace to get a list of individual items.
for person, devices in persons.items():
devices = devices[0].split(", ")
if len(devices) == 1:
print(f"{person}'s favorite item is: {devices[0]}")
elif len(devices) > 1:
print(f"{person}'s favorite items are: {devices}")
CodePudding user response:
You are iterating the lists already. Remove the second loop:
for person, devices in persons.items():
devices = devices[0].split(', ')
if len(devices) == 1:
print(f"{person}'s favorite item is: {device[0]}")
elif len(devices) > 1:
print(f"{person}'s favorite items are:")
for device in devices:
print(device)
CodePudding user response:
If really the input is made of single string in lists, use string methods:
for person, devices in persons.items():
several = ',' in devices[0]
verb = 'are:\n' if several else 'is:'
devs = devices[0].replace(', ', '\n')
print(f"{person}'s favorite item {verb} {devs}")
Output:
Rondo's favorite item are:
computer
pc
phone
ps5
ps4
Lebron's favorite item is: pc
Kobe's favorite item is: cellphone
Ronel's favorite item are:
Laptop
Phone