Python-Ref > Data structures > Dictionaries > Dictionary convenience functions
 
 

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

Dictionary convenience functions

The dictionary object has several methods for convenient manipulation. Some of them were already presented on other slides - items, iteritems, keys, values.
The update methods lets you merge one dictionary into the other. As well as in the case of dictionary creation the update method also works with lists of key-value pairs.
Expand/Shrink
Zdroj: (dict6-1.py)
  1   # creation of a dictionary
  2   name2age = {"Jane": 21, "Lucy": 34, "David": 1}
  3   name2age2 = {"Tom": 5, "Peter": 6}
  4   print name2age
  5   
  6   name2age.update( name2age2)
  7   print name2age
  8   
  9   # update using key-value pairs
 10   name2age.update( [("John", 89), ("Amy", 25)])
 11   print name2age
stdout:
{'Jane': 21, 'Lucy': 34, 'David': 1}
{'Jane': 21, 'Peter': 6, 'Tom': 5, 'Lucy': 34, 'David': 1}
{'John': 89, 'Lucy': 34, 'David': 1, 'Amy': 25, 'Tom': 5, 'Jane': 21, 'Peter': 6}
Doba běhu: 21.1 ms
The fromkeys method lets you create a dictionary with keys taken from a sequence and value set to a default value.
Expand/Shrink
Zdroj: (dict6-2.py)
  1   letters = "abcdefgh"
  2   
  3   letter2count = {}.fromkeys( letters, 0)
  4   print letter2count
  5   
  6   
  7   names = ["John","Peter","Jack","David"]
  8   name2salary = {}.fromkeys( names, 10000)
  9   print name2salary
 10   name2salary[ "John"] = 5000
 11   print name2salary
stdout:
{'a': 0, 'c': 0, 'b': 0, 'e': 0, 'd': 0, 'g': 0, 'f': 0, 'h': 0}
{'John': 10000, 'Jack': 10000, 'Peter': 10000, 'David': 10000}
{'John': 5000, 'Jack': 10000, 'Peter': 10000, 'David': 10000}
Doba běhu: 21.5 ms
Get method is very useful when not sure if a retrieved value is in the dictionary.
The following code shows a typical example of condition that is used when iterating over values that might be in a directory.
Expand/Shrink
Zdroj: (dict6-3.py)
  1   name2salary = {"Jane": 21000, "Lucy": 34000, "David": 10000, "Tom": 50000, "Peter": 6000}
  2   
  3   for n in ["Lucy","John","Norma"]:
  4     if n in name2salary:
  5       print n, name2salary[ n]
  6     else:
  7       print n, 0
stdout:
Lucy 34000
John 0
Norma 0
Doba běhu: 21.1 ms
This much simplified code shows the same functionality using the get method.
Expand/Shrink
Zdroj: (dict6-4.py)
  1   name2salary = {"Jane": 21000, "Lucy": 34000, "David": 10000, "Tom": 50000, "Peter": 6000}
  2   
  3   for n in ["Lucy","John","Norma"]:
  4     print n, name2salary.get( n, 0)
stdout:
Lucy 34000
John 0
Norma 0
Doba běhu: 20.5 ms