Home > Back-end >  Looping through a dictionary to print out statements based on number of items in the list from the d
Looping through a dictionary to print out statements based on number of items in the list from the d

Time:10-26

I am trying to figure out how to an if/else or if/elif statement along with a for loop in python to loop through a program to print out a statement based on the number of items in a list for the value from the key value pairs. .

favoritePlaces = {
    'tom': ['alaska', 'wales', 'italy',],
    'rory': ['hawaii',],
    'frank': ['greenland', 'south africa',],
    }

lengths = {key:len(value) for key,value in favoritePlaces.items()}
print(lengths.values())

for person, places in favoritePlaces.items():
    if length in lengths.values() > 1:
        print(f"\n{person.title()}'s favorite places are:")
        for place in places:
            print(f"\t- {place.title()}")
    else:
        print(f"\n{person.title()}'s favorite place is:")
        for place in places:
            print(f"\t- {place.title()}")
 

The output should look like this:

Tom's favorite places are: - Alaska - Wales - Italy

Rory's favorite place is: - Hawaii

Frank's favorite places are: - Greenland - South Africa


I have tried placing the for loops and if statements in different configurations to try and get it to work. Every configuration gives me length not defined. I have looked though stackoverflow for an answer and that is where I put in the lengths variable hoping the would help. I am fairly new to coding and trying to learn and I am not sure if I put in the wrong search parameters.

Any help would be greatly appreciated, and thanks in advance. 

CodePudding user response:

How about this:

for person, places in favoritePlaces.items():
    places_len = len(places) # Check the length of places
    if places_len > 1:
        print(f"\n{person.title()}'s favorite places are:")
        for place in places:
            print(f"\t- {place.title()}")
    else:
        print(f"\n{person.title()}'s favorite place is:")
        for place in places:
            print(f"\t- {place.title()}")

CodePudding user response:

You can check whether places is None or an empty list:

favoritePlaces = {
    'tom': ['alaska', 'wales', 'italy',],
    'rory': ['hawaii',],
    'frank': ['greenland', 'south africa',],
    'test1': None,
    'test2': [],
    }

for person, places in favoritePlaces.items():
    if places:
        print(f"\n{person.title()}'s favorite place(s):")
        for place in places:
            print(f"\t- {place.title()}")
    else:
        print(f"\n{person.title()} does not have any favorite place")

Output:

enter image description here

  • Related