Iterating over dictionaries using for loops

0 votes

I am a bit puzzled by the following 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?

Oct 8, 2018 in Python by ana1504.k
• 7,910 points
977 views

1 answer to this question.

0 votes
key is just a variable name.

for key in d:
will simply loop over the keys in the dictionary, rather than the keys and values. To loop over both key and value you can use the following:

For Python 2.x:

for key, value in d.iteritems():
For Python 3.x:

for key, value in d.items():
answered Oct 8, 2018 by SDeb
• 13,300 points

Related Questions In Python

0 votes
1 answer

Iterating over dictionaries using 'for' loops

Here in this example the key is ...READ MORE

answered Feb 11, 2022 in Python by Dev
• 6,000 points
460 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,100 points
1,469 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,223 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,441 views
0 votes
1 answer

Section postgresql not found in the database.ini file

Python doesn't know what $FILEDIR is. Try an absolute path ...READ MORE

answered Oct 3, 2018 in Python by Priyaj
• 58,100 points
3,643 views
0 votes
1 answer

Conflicting dependencies of pypyodbc and blpapi

I figured out that pypyodbc only works ...READ MORE

answered Oct 9, 2018 in Python by Priyaj
• 58,100 points
735 views
0 votes
1 answer

How to sort dictionary by value python

This would work: d = sorted(data, key = ...READ MORE

answered Nov 2, 2018 in Python by Nabarupa
711 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,007 views
0 votes
1 answer

How to download a file over HTTP using Python?

In Python 2, use urllib2 which comes ...READ MORE

answered Oct 18, 2018 in Python by SDeb
• 13,300 points
841 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