python 如何循环访问字典中的值

eyh26e7m  于 2023-03-16  发布在  Python
关注(0)|答案(2)|浏览(142)
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']

这是代码,我知道我的错误在迭代的某个地方,但是不知道如何修复它
我以为添加另一个for i in range()并进行4次迭代会打印出适当的结果,但它没有。我只得到了非洲的值,没有其他值。

olmpazwi

olmpazwi1#

问题是在第一次循环迭代时返回一个值,这将退出整个函数,而您希望累加result中的值的字符串,然后在函数结束时(循环外)调用return result
你也可以简化你的代码,就像这样:

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"]}))
szqfcxe2

szqfcxe22#

最简单的迭代代码基本上只有两行,并且不进行函数调用:

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

注意“values()”方法调用。
如果您更喜欢使用函数调用,则以下代码将实现相同的结果:

# 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())

请注意,它不是“print(countries...)”,而只是“countries()”。

相关问题