Home > OS >  Accessing dictionary W/ Nested loops - Python
Accessing dictionary W/ Nested loops - Python

Time:11-06

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.

Carrots are Vegetables
Apples are fruits

CodePudding user response:

Have a look at the items() method of dict. 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.

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]; as you see in my example above, items() is much nicer since it will give you both at the same time.

CodePudding user response:

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

CodePudding user response:

You might try:

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

CodePudding user response:

You can use dict.items().

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

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

Output:

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

CodePudding user response:

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']
  • Related