How to iterate through values in a dictionary

def countries(countries_dict):
    result = " "
    # Complete the for loop to iterate through the key and value items 
    # in the dictionary.

    for keys in countries_dict.values():
            for i in range(1,4):
                result += str(keys)
                return result

print(countries({"Africa": ["Kenya", "Egypt", "Nigeria"], "Asia":["China", "India", "Thailand"], "South America": ["Ecuador", "Bolivia", "Brazil"]}))

# Should print:
# ['Kenya', 'Egypt', 'Nigeria']
# ['China', 'India', 'Thailand']
# ['Ecuador', 'Bolivia', 'Brazil']

This is the code. I know my mistake is somewhere in the iteration but have no idea how to fix it

I thought adding another for i in range() and making iterate 4 times would print the appropriate result but it didn’t. I’m only getting the values from Africa and no other ones.

>Solution :

The issue is that you return a value during the first loop iteration, which exits the whole function. Instead, you want to accumulate the strings of the values in result, then call return result at the end of the function (outside of the loop).

You can also simplify your code a bit. Like this:

def countries(countries_dict):
    result = ""
    for lst in countries_dict.values():
        result += str(lst) + '\n'
    return result[:-1]


print(countries({"Africa": ["Kenya", "Egypt", "Nigeria"],
                 "Asia":["China", "India", "Thailand"],
                 "South America": ["Ecuador", "Bolivia", "Brazil"]}))

Leave a Reply