简体   繁体   English

访问带有嵌套循环的字典 - Python

[英]Accessing dictionary W/ Nested loops - Python

dic = {"Vegetables":["Carrots","Broccoli","Mushrooms"], "fruits":["Apples ","Citrus"]}
for itm in dic: 
    for val in dic.values():
        print("{} are {}".format(dic[itm][val]))

How would I print ex.我将如何打印 ex。

Carrots are Vegetables
Apples are fruits

Have a look at the items() method of dict.看看 dict 的items()方法。 It will let you iterate over its keys and values.它会让你迭代它的键和值。

So each key will be a string, and each value a list - you do not need to call any methods besides items() in your code, and you do not need to use [] anywhere.所以每个键都是一个字符串,每个值都是一个列表——你不需要在代码中调用除items()之外的任何方法,也不需要在任何地方使用[]

for key, value in dic.items():
    for item in value:
        print(f'{item} are {key}')

A tip since you are clearly a Python beginner: Iterating over dict keys only ( for key in somedict ) is something you rarely do in Python - especially if the first thing inside that loop is something like value = somedict[key] ;提示,因为您显然是 Python 初学者:仅迭代 dict 键( for key in somedict )是您在 Python 中很少做的事情 - 特别是如果该循环中的第一件事是类似value = somedict[key] as you see in my example above, items() is much nicer since it will give you both at the same time.正如你在我上面的例子中看到的, items()更好,因为它可以同时给你两个。

The first loop should iterate through the keys, while the second loop goes through the corresponding values.第一个循环应该遍历键,而第二个循环遍历相应的值。 As it stands now, your loops are disconnected.就目前而言,您的循环已断开连接。

dic = {"Vegetables": ["Carrots", "Broccoli", "Mushrooms"], "fruits": ["Apples ", "Citrus"]}
for itm in dic:  # iterate through keys
    for val in dic[itm]:  # iterate through list corresponding to the key
        print("{} are {}".format(val, itm))  # print

Result:结果:

Carrots are Vegetables
Broccoli are Vegetables
Mushrooms are Vegetables
Apples  are fruits
Citrus are fruits

You might try:你可以试试:

for key, values in dic.items():
    for val in values:
        print('{val} are in {key}'.format(val=val, key=key))

You can use dict.items() .您可以使用dict.items()

dic = {"Vegetables":["Carrots","Broccoli","Mushrooms"], "fruits":["Apples ","Citrus"]}

for category, lst in dic.items():
    for thing in lst:
        print(f"{thing} are {category}")

Output:输出:

Carrots are Vegetables
Broccoli are Vegetables
Mushrooms are Vegetables
Apples  are fruits
Citrus are fruits

How about this?这个怎么样?

dic = {"Vegetables":["Carrots","Broccoli","Mushrooms"], "fruits":["Apples ","Citrus"]}
for key, value in dic.items():
    print(f'key is {key}, value is {value}')

key is Vegetables, value is ['Carrots', 'Broccoli', 'Mushrooms']
key is fruits, value is ['Apples ', 'Citrus']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM