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,890 points
63 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,190 points

Related Questions In Python

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
• 56,940 points
89 views
0 votes
1 answer

Iterating over multiple lists

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

answered Apr 25, 2018 in Python by Nietzsche's daemon
• 4,260 points
38 views
+1 vote
1 answer

Accessing the index in 'for' loops?

Using an additional state variable, such as ...READ MORE

answered Aug 28, 2018 in Python by Priyaj
• 56,940 points
39 views
0 votes
1 answer

Python: nested 'for' loops

Could use itertools: >>> for comb in itertools.combinations_with_replacement(range(9, -1, ...READ MORE

answered Sep 3, 2018 in Python by Priyaj
• 56,940 points
96 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
• 56,940 points
256 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
• 56,940 points
105 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
78 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 21, 2018 in Python by SDeb
• 13,190 points
71 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,190 points
62 views