Python - Data Type Iterate dictionary

Introduction

The following code steps through the keys of a dictionary.

It requests its keys list explicitly:

Demo

D = {'a':1, 'b':2, 'c':3} 
for key in D.keys(): 
    print(key, D[key])

Result

Dictionaries are iterables with an iterator that automatically returns one key at a time in an iteration context:

Demo

D = {'a':1, 'b':2, 'c':3} 
I = iter(D) #  ww  w  .  j a  v a2  s .  com
print( next(I) )
print( next(I) )
print( next(I) )
print( next(I) )

Result

for loop will use the iteration protocol to grab one key each time through:

Demo

D = {'a':1, 'b':2, 'c':3} 
for key in D: 
     print(key, D[key])

Result

Related Topic