Python-Ref > Data structures > Dictionaries > Iterating over a dictionary
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

Iterating over a dictionary

In Dictionary introduction we have seen one way of iteration over a dictionary by iterating over its keys.
Expand/Shrink
Zdroj: (dict2-1.py)
  1   name2age = {"Jane": 21, "Lucy": 34, "David": 1, "Tom": 5, "Peter": 6}
  2   
  3   for name in name2age.keys():
  4       print name, name2age[ name]
stdout:
Jane 21
Tom 5
Lucy 34
Peter 6
David 1
Doba běhu: 21.0 ms
We get the same behavior if we omit the keys method.
Expand/Shrink
Zdroj: (dict2-2.py)
  1   name2age = {"Jane": 21, "Lucy": 34, "David": 1, "Tom": 5, "Peter": 6}
  2              
  3   for name in name2age:   # by default iterate over the keys
  4       print name, name2age[ name]
stdout:
Jane 21
Tom 5
Lucy 34
Peter 6
David 1
Doba běhu: 21.2 ms
Most often we will use both the key and the associated value in the loop. To simplify this case, dictionary object provides the iteritems method that returns a list of (key,value) pairs. These can be used in a kind of tuple unpacking directly in the for loop.
Expand/Shrink
Zdroj: (dict2-3.py)
  1   name2age = {"Jane": 21, "Lucy": 34, "David": 1, "Tom": 5, "Peter": 6}
  2              
  3   for (name, age) in name2age.iteritems():   # iterate over (key, value) pairs
  4       print name, age
stdout:
Jane 21
Tom 5
Lucy 34
Peter 6
David 1
Doba běhu: 21.0 ms