Python - For each pair in dictionary

Introduction

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:

Demo

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  ava 2s .  c om
print( list(D.items())  )

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

Result

Related Example