Python - For each pair in dictionary


Tuples in for loops can iterate through both keys and values in dictionaries using the items method, rather than looping through the keys and indexing to fetch the values manually:


D = {'a': 1, 'b': 2, 'c': 3} 
for key in D: 
   print(key, '=>', D[key])             # Use dict keys iterator and index 
# from  w  w w  . j a v  a 2s  .  c  o m
print( list(D.items())  )

for (key, value) in D.items(): 
   print(key, '=>', value)              # Iterate over both keys and values


Related Example