Dictionary Operations

 

Here is a quick run-through of the operations you can do on dictionaries.  While lists and tuples associate values with indices, dictionaries associate values with keys.  Any immutable type (including tuples and strings) can be used as keys.

 

A.     Making dictionaries:

D = {}  (the empty dictionary, which has no elements)

D = {“White Sox”: 2, “Angels”: 1} is a dictionary with two elements

D = dict(zip([“White Sox”, “Angles”], [2, 1]) )  makes the same dictionary

 

B.  Indexing and Keys:

D[“Angels”] is the value associated with the key “Angels”.  This causes a crash if  Angels” is not a key. 

D.get(“Angels”, 0) is the same as D[“Angels”], only if “Angels” is not a key this returns value 0 (called the default value).

           

C.  Changing the contents of the dictionary
D[“Angles”] = 3 changes the value associated with key “Angels”.  If there is no such value it makes a new entry in the dictionary associating 3 with “Angels”.

 

C.     Other stuff

len(D): the length, or number of entries, of D

D.has_key(“Angels”) : returns True if D has an entry whose key is “Angels”

D.keys() returns the list of all keys of D.

D.values() returns the list of all values of D.

D.copy() returns a copy of D

D.update(E) adds all of the entries of dictionary E to dictionary D.