0 votes
1 view
in Python by (3.4k points)
edited by

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?

1 Answer

0 votes
by (46.1k points)
edited by

Key is a variable, The insertion order preservation nature of dictionary objects, so when an user iterate through dictionaries using some syntax  like for or in it iterates over the keys.

For different python versions their exist different syntax:

For Python 2.x use:

for key, value in d.iteritems():

for Python 3.x use:

for key, value in d.items():

You can also refer to Python documentation for assistance. 

To know more about this you can have a look at the following video tutorial:-

Related questions

+5 votes
2 answers
0 votes
1 answer
asked Sep 30, 2019 in Python by Sammy (47.8k points)
+1 vote
1 answer
0 votes
2 answers
asked Jul 15, 2019 in Python by Sammy (47.8k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...