Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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"]}))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading