How to iterate through values in a dictionary

Question:

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.

Asked By: EdBoi4

||

Answers:

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"]}))
Answered By: Michael M.

The simplest iterative code basically takes two lines, and does not make a function call:

for x in {"Africa": ["Kenya", "Egypt", "Nigeria"], 
             "Asia":["China", "India", "Thailand"], 
             "South America": ["Ecuador", "Bolivia", "Brazil"]}.values():
    print(x)

Note the ‘values()’ method call.

If you prefer to use a function call, then the following code will achieve the same result:

# define the function (printing happens in here)
def countries(countries_view):
        for x in countries_view:
            print(x)

# call the function, no printing at this level, printing is done in the function
countries({"Africa": ["Kenya", "Egypt", "Nigeria"], 
             "Asia":["China", "India", "Thailand"], 
             "South America": ["Ecuador", "Bolivia", "Brazil"]}.values())

Note that it is NOT ‘print(countries…)’ but just ‘countries()’.

Answered By: Intercooler Turbo
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.