Create a dictionary

Documentation

  1. Class dictionary (and class dictionary view) in the Python Standard Library
  2. Dictionaries in the Python Tutorial
  3. Dictionaries in the Python Language Reference
  4. dictionary (and dictionary view) in the Python Glossary
  5. Subclasses of class dict in the Python Standard Library:
    1. collections.defaultdict
    2. collections.OrderedDict
    3. collections.Counter

Two parallel columns

A for loop (line 26) can have an else section (line 30).

do1.py

Please type a note (e.g., do): so
So, a needle pulling thread.

Please type a note (e.g., do): me
Me, a name I call myself.

Please type a note (e.g., do): tee
Sorry, "tee" is not a note.

A dictionary

A dictionary is like a list or tuple that contains two parallel columns. The left column is the column of keys. The right column is the column of values. The two columns must contain the same number of items. We look up a key in order to find the corresponding value.

In the following example, the keys are strings and the values are strings. But in another dictionary, the keys and values could be other data types. For example, the keys could be strings and the values could be ints. In real life, however, the keys will usually be strings.

do2.py

Please type a note (e.g., do): so
So, a needle pulling thread.

Please type a note (e.g., do): me
Me, a name I call myself.

Please type a note (e.g., do): tee
Sorry, "tee" is not a note.

Things to try

  1. Another way to test for input that is not a valid note is to replace the EAFP code in lines 25–33 of do2.py with the following LBYL code.
        if note in notes:            #if note is one of the keys of the dict:
            definition = notes[note] #could also say definition = notes.get(note)
            print(f"{note.capitalize()}, a {definition}.")
        else:
            print(f'Sorry, "{note}" is not a note.')
    
        print()
    

    Why does Python have the function get that does (almost) the same thing as the [square brackets]? See exercise 4 below.

  2. Loop through the keys of the dictionary. You can use each key to get the corresponding value. This for loop and the ones below with items print all the items in the dictionary, and Python 3.7 even guarantee that the items will be printed in the order in which they were inserted. But if you frequently loop through the dictionary, or frequently rearrange the order of its items, it might be faster to use a collections.OrderedDict.

    for key in notes:   #could also say for key in notes.keys():
        print(key, notes[key])
    
    do deer, a female deer
    re drop of golden sun
    me name I call myself
    fa long, long way to run
    so needle pulling thread
    la note to follow so
    ti drink with jam and bread
    
    If all you want are these keys and values in their original order, exercise 6 below is a simpler way to loop through them.
  3. Loop through the keys in sorted order. Since the keys of this dictionary are strings, their sorted order is alphabetical order, not numerical order. The sorted function returns a list of strings, even though notes is a dict.
    for key in sorted(notes):
        print(key, notes[key])
    
    do deer, a female deer
    fa long, long way to run
    la note to follow so
    me name I call myself
    re drop of golden sun
    so needle pulling thread
    ti drink with jam and bread
    
  4. Loop through the keys in sorted order of their corresponding values. Since the values in this dictionary are strings, their sorted order is alphabetical order, not numerical order.
    for key in sorted(notes, key = notes.get):
        print(key, notes[key])
    
    do deer, a female deer
    ti drink with jam and bread
    re drop of golden sun
    fa long, long way to run
    me name I call myself
    so needle pulling thread
    la note to follow so
    
  5. Loop through the keys in order of increasing length of the corresponding values:
    def score(key):
        "Return the length of the value corresponding to this key."
        return len(notes.get(key))
    
    for key in sorted(notes, key = score):
        print(key, notes[key])
    
    Or with a lambda function:
    for key in sorted(notes, key = lambda key: len(notes.get(key))):
        print(key, notes[key])
    
    la note to follow so
    re drop of golden sun
    me name I call myself
    do deer, a female deer
    fa long, long way to run
    so needle pulling thread
    ti drink with jam and bread
    
  6. items returns a list of tuples (or at least an iterable of tuples). Each of these tuples consists of a key and the corresponding value.
    for item in notes.items():    #item is a tuple.
        print(item[0], item[1])   #item[0] and item[1] are strings.
    
    do deer, a female deer
    re drop of golden sun
    me name I call myself
    fa long, long way to run
    so needle pulling thread
    la note to follow so
    ti drink with jam and bread
    
    We could also write the loop this way. We saw a two-variable for loop with enumerate in For char, and with zip in Zip. The parentheses immediately after the word for are optional.
    for (key, value) in notes.items():
        print(key, value)
    
    do deer, a female deer
    re drop of golden sun
    me name I call myself
    fa long, long way to run
    so needle pulling thread
    la note to follow so
    ti drink with jam and bread
    
  7. Add line numbers. Also see the reverse dictionary googletrans.LANGCODES.
    pip3 install googletrans
    
    """
    Print the iso639-1 language codes.  Parens around (key, value) are required.
    """
    
    import sys
    import googletrans
    
    for key, value in googletrans.LANGUAGES.items():
        print(f"{key:5} {value}")
    
    sys.exit(0)
    
    af    afrikaans
    sq    albanian
    am    amharic
    ar    arabic
    hy    armenian
    etc.
    he    Hebrew
    
    """
    Print the iso639-1 language codes.
    """
    
    import sys
    import googletrans
    
    #Parentheses necessary around key, value.
    
    for i, (key, value) in enumerate(googletrans.LANGUAGES.items(), start = 1):
        print(f"{i:3} {key:5} {value}")
    
    sys.exit(0)
    
      1 af    afrikaans
      2 sq    albanian
      3 am    amharic
      4 ar    arabic
      5 hy    armenian
    etc.
    106 he    Hebrew
    
  8. Another predefined dictionary is http.server.BaseHTTPRequestHandler.responses; see One big sequence of bytes. Each value in this dictionary is a tuple of two strings, value[0] and value[1].
    import http.server
    
    for key, value in http.server.BaseHTTPRequestHandler.responses.items():
        print(int(key), value[0])
        if value[1]:   #or if value[1] != "":
            print(value[1])
        print()
    
    100 Continue
    Request received, please continue
    
    101 Switching Protocols
    Switching to new protocol; obey Upgrade header
    
    102 Processing
    
    200 OK
    Request fulfilled, document follows
    
    201 Created
    Document created, URL follows
    
  9. Make a dictionary whose keys and values are names and phone numbers.
    directory = {
        "John":  "212-234-5678",
        "Sally": "914-876-5432",
        #etc.
    
  10. Make a dictionary that translates IKEA language into English. (Or vice versa.)
  11. [The Elephant and the Polish Question.] Make a dictionary loosely based on the story about the international symposium on elephants. The German scholar presented a paper entitled Some Observations Preliminary to the Compilation of a Definitive Bibliography on the Elephant. The French scholar presented a paper called The Love Life of the Elephant. The Englishman presented Hunting and Trapping the Elephant in his Native Habitats and the American team offered How to Grow Bigger and Better Elephants. Finally, the Polish scholar ended the conference with a paper entitled The Elephant and the Polish Question. (Alternative ending: The Elephant and the Jewish Question.)
  12. The keys of a dictionary must be hashable. See hash and __hash__.
    import sys
    
    #See if a string is hashable.
    s = "hello"   #also try s = [10, 20, 30]
                  #also try s = {10, 20, 30}
    
    try:
        h = hash(s)
    except TypeError as error:
        print(f"Sorry, an object of {type(s)} is not hashable:", error, file = sys.stderr)
    else:
        print(f"An object of {type(s)} is hashable, and this object hashed to {h:,}.")
    
    An object of <class 'str'> is hashable, and this object hashed to 2,110,794,038,273,648,352.
    
    Sorry, an object of <class 'list'> is not hashable: unhashable type: 'list'
    
    Sorry, an object of <class 'set'> is not hashable: unhashable type: 'set'