Iterating over dictionaries using for loops

0 votes

Here is the code:

d = {'x': 1, 'y': 2, 'z': 3} 
for key in d:
    print (key, 'corresponds to', d[key])

What I don't understand is the key portion. How does Python recognize that it needs only to read the key from the dictionary? Is key a special word in Python? Or is it simply a variable?

Feb 11, 2022 in Python by Nandini
• 5,480 points
500 views

1 answer to this question.

0 votes

Here in this example the key is used as a variable, it is not a keyword.Since you have defined a dictionary, the syntax is {‘Key’ : ‘Value’} key and value pair separated by colon (:)
You can use other word instead of Key and the output will be the same

d = {'x': 1, 'y': 2, 'z': 3} 
for value in d:
    print( value, 'corresponds to', d[value])


Since Dictionary has keys and values that can be retrieved in Python using:

d.keys()

Output

dict_keys(['x', 'y', 'z'])
d.values()

Output

dict_values([1, 2, 3])
answered Feb 11, 2022 by Dev
• 6,000 points

Related Questions In Python

0 votes
1 answer

Iterating over dictionaries using 'for' loops

key is just a variable name. for key ...READ MORE

answered Oct 8, 2018 in Python by SDeb
• 13,300 points
1,003 views
0 votes
1 answer

How can I Iterate over dictionaries using 'for' loops

key is just a variable name. for key in ...READ MORE

answered Oct 17, 2018 in Python by Priyaj
• 58,020 points
1,496 views
0 votes
1 answer

Return a list inside a for loop while iterating over the elements of another list

The print() is getting called multiple times ...READ MORE

answered Sep 22, 2018 in Python by SDeb
• 13,300 points
5,062 views
+1 vote
1 answer

instead of using two for loops in python

This example might help: for x, y in ((a,b) ...READ MORE

answered Dec 24, 2019 in Python by Sumeir
1,305 views
0 votes
1 answer

Iterating over multiple lists

import itertools for item in itertools.chain(listone, listtwo): #li ...READ MORE

answered Apr 25, 2018 in Python by Nietzsche's daemon
• 4,260 points
1,489 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,466 views
0 votes
1 answer
0 votes
1 answer

What is the python keyword "with" used for?

The PEP343 documentation contains details regarding the ...READ MORE

answered Feb 9, 2022 in Python by Dev
• 6,000 points
742 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP