For loop with Dictionary

Traverse a dictionary with for loop Accessing keys and values in dictionary. Use Dict.values() and Dict.keys() to generate keys and values as iterable. Nested Dictionaries with for loop Access Nested values of Nested Dictionaries How useful was this post? Click on a star to rate it! Submit Rating

Topics:

Traverse a dictionary with for loop

dict={1:'one',2:'two',3:'three',4:'four',
      5:'five',6:'six',7:'seven',8:'eight',
      9:'nine',10:'ten'}
dict

O/P:
{1: 'one',
 2: 'two',
 3: 'three',
 4: 'four',
 5: 'five',
 6: 'six',
 7: 'seven',
 8: 'eight',
 9: 'nine',
 10: 'ten'}

for i in dict:
    print(dict[i])
O/P:
one
two
three
four
five
six
seven
eight
nine
ten

Accessing keys and values in dictionary.

for i in dict:
    print(i,dict[i])
O/P:
1 one
2 two
3 three
4 four
5 five
6 six
7 seven
8 eight
9 nine
10 ten

Use Dict.values() and Dict.keys() to generate keys and values as iterable.

for key in dict.keys():
    print(key)
O/P:

1
2
3
4
5
6
7
8
9
10

for value in dict.values():
    print(value)
O/P:

one
two
three
four
five
six
seven
eight
nine
ten

Nested Dictionaries with for loop

Access Nested values of Nested Dictionaries

dict={
    'Apple':{'color':'red','taste':'sweet'},
    'Lemon':{'color':'yellow','taste':'sour'},
    'Cherry':{'color':'red','taste':'sweet'},
}
for i in dict:
    print(i)
    for j in dict[i]:
        print(j,dict[i][j])
    print()
O/P:
Apple
color red
taste sweet

Lemon
color yellow
taste sour

Cherry
color red
taste sweet

How useful was this post?

Click on a star to rate it!

Instagram
WhatsApp
error: Content is protected !!