Jump to content

Python Programming/Dictionaries

From Wikiversity

This lesson introduces Python dictionaries.

Objectives and Skills

[edit | edit source]

Objectives and skills for this lesson include:[1]

  • Data Structures
    • Dictionary

Readings

[edit | edit source]
  1. Wikipedia: Dictionary (data structure)
  2. Python for Everyone: Dictionaries

Multimedia

[edit | edit source]
  1. YouTube: Python for Informatics - Chapter 9 - Dictionaries
  2. YouTube: Python Dictionary
  3. YouTube: Python - Min, Max, and Sorting Dictionaries
  4. YouTube: Python Dictionaries Playlist

Examples

[edit | edit source]

Dictionaries

[edit | edit source]

Dictionaries are collections that are indexed by keys, which can be any immutable type. It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary). Placing a comma-separated list of key:value pairs within braces adds initial key:value pairs to the dictionary.[2]

dictionary = {
    'cat': 'Frisky',
    'dog': 'Spot',
    'fish': 'Bubbles',
}

print("dictionary:", dictionary)
print("dictionary['cat']:", dictionary['cat'])
print("dictionary['dog']:", dictionary['dog'])
print("dictionary['fish']:", dictionary['fish'])

Output:

dictionary: {'dog': 'Spot', 'fish': 'Bubbles', 'cat': 'Frisky'}
dictionary['cat']: Frisky
dictionary['dog']: Spot
dictionary['fish']: Bubbles

Dictionary Updates

[edit | edit source]

A pair of braces creates an empty dictionary: {}. Dictionary items may be added, updated, and deleted by key.[3]

dictionary = {}
dictionary['cat'] = 'Frisky'
dictionary['dog'] = 'Spot'
dictionary['fish'] = 'Bubbles'
print("dictionary:", dictionary)

dictionary['dog'] = 'Rover'
print("dictionary:", dictionary)

del dictionary['fish']
print("dictionary:", dictionary)

Output:

dictionary: {'cat': 'Frisky', 'fish': 'Bubbles', 'dog': 'Spot'}
dictionary: {'cat': 'Frisky', 'fish': 'Bubbles', 'dog': 'Rover'}
dictionary: {'cat': 'Frisky', 'dog': 'Rover'}

Multidimensional Dictionaries

[edit | edit source]

Dictionaries may be nested.

dictionary = {
    'John': {'name': 'John Smith', 'phone': '123-555-0101'}, 
    'Jose': {'name': 'Jose Garcia', 'phone': '123-555-0102'}
}

print("John's name:", dictionary['John']['name'])
print("Jose's phone:",dictionary['Jose']['phone'])

Output:

John's name: John Smith
Jose's phone: 123-555-0102

Looping

[edit | edit source]

Dictionary items may be accessed with a for loop.

dictionary = {
    'cat': 'Frisky',
    'dog': 'Spot',
    'fish': 'Bubbles',
}

for key in dictionary:
    print("dictionary[%s]: %s" % (key, dictionary[key]))

Output:

dictionary[dog]: Spot
dictionary[fish]: Bubbles
dictionary[cat]: Frisky

Sorting by Key

[edit | edit source]

Dictionaries are unordered. Dictionary items may be displayed in key order by sorting a list of keys using the sorted() function and the dictionary.keys() method.[4]

dictionary = {
    'cat': 'Frisky',
    'dog': 'Spot',
    'fish': 'Bubbles',
}

for key in sorted(dictionary.keys()):
    print("dictionary[%s]: %s" % (key, dictionary[key]))

Output:

dictionary[cat]: Frisky
dictionary[dog]: Spot
dictionary[fish]: Bubbles

Sorting by Value

[edit | edit source]

Dictionaries are unordered. Dictionary items may be displayed in value order by sorting a list of key-value pairs using the sorted() function and the dictionary.get() method.[5]

dictionary = {
    'cat': 'Frisky',
    'dog': 'Spot',
    'fish': 'Bubbles',
}

for key in sorted(dictionary, key=dictionary.get):
    print("dictionary[%s]: %s" % (key, dictionary[key]))

Output:

dictionary[fish]: Bubbles
dictionary[cat]: Frisky
dictionary[dog]: Spot

Dictionary as Return Value

[edit | edit source]

Functions may return multiple values using a dictionary.[6]

def function(x, y):
    ...
    return {'x': x, 'y': y}

Activities

[edit | edit source]

Tutorials

[edit | edit source]
  1. Complete one or more of the following tutorials:

Practice

[edit | edit source]
  1. Create a Python program that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then use a loop to request each score and add it to a dictionary, counting how many times each score is entered. Finally, use a function to display the dictionary of entered scores sorted in descending order and a histogram showing how many times each score was entered. Include try and except to handle input errors. For example:
        100: *
        90: ***
        80: *****
        70: **
  2. Create a Python program that asks the user to enter a line of comma-separated grade scores. Use the string split() method to parse the line and add each score to a dictionary, counting how many times each score is entered. Finally, use a function to display the list of entered scores sorted in descending order and a histogram showing how many times each score was entered. Include try and except to handle input errors. For example:
        100: *
        90: ***
        80: *****
        70: **
  3. Create a Python program that asks the user to enter a line of text. Use the string split() method to parse the line and add each word to a dictionary, counting how many times each word is entered. Convert words to lower case and remove any punctuation to prevent duplicate or invalid results. Finally, use a function to display the list of entered words sorted in alphabetical order and a histogram showing how many times each word was entered. Include try and except to handle input errors. For example:
        cat: *
        hat: *
        in: *
        the: **
  4. Create a Python program that asks the user for a line of text that contains HTML tags, such as:
        <p><strong>This is a bold paragraph.</strong></p>
    Use string methods to search for and remove all HTML tags from the text, saving each removed tag in a dictionary. Print the untagged text and then use a function to display the list of removed tags sorted in alphabetical order and a histogram showing how many times each tag was used. Include error handling in case an HTML tag isn't entered correctly (an unmatched < or >). Use a user-defined function for the actual string processing, separate from input and output. For example:
        </p>: *
        </strong>: *
        <p>: *
        <strong>: *

Lesson Summary

[edit | edit source]

Dictionary Concepts

[edit | edit source]
  • A dictionary or associative array is a data type composed of a collection of (key: value) pairs, such that each possible key appears at most once in the collection.[7]
  • Dictionary operations include:[8]
    • the addition of a pair to the collection
    • the removal of a pair from the collection
    • the modification of an existing pair
    • the lookup of a value associated with a particular key
  • Dictionaries are typically implemented in programming languages as either a hash table or a search tree.[9]
  • A hash table uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found.[10]
  • A hash function is any function that can be used to map data of arbitrary size to data of fixed size.[11]
  • A good hash function should map the expected inputs as evenly as possible over its output range.[12]

Python Dictionaries

[edit | edit source]
  • Dictionaries are collections that are indexed by keys, which can be any immutable type.[13]
  • It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary).[14]
  • Placing a comma-separated list of key:value pairs within braces adds initial key:value pairs to the dictionary using the syntax dictionary = {key: value, key: value}.[15]
  • A pair of braces creates an empty dictionary: {}. Dictionary items may be added, updated, and deleted by key using the syntax dictionary[key] = value and del dictionary[key].[16]
  • Dictionaries may be nested and are accessed using the syntax dictionary[key][subkey]
  • Dictionary items may be accessed with a for loop.
  • Dictionaries are unordered. Dictionary items may be displayed in key order by sorting a list of keys using the sorted() function and the dictionary.keys() method.[17]
  • Dictionaries are unordered. Dictionary items may be displayed in value order by sorting a list of key-value pairs using the sorted() function and the dictionary.get() method.[18]

Key Terms

[edit | edit source]
dictionary
A mapping from a set of keys to their corresponding values.[19]
hashtable
The algorithm used to implement Python dictionaries.[20]
hash function
A function used by a hashtable to compute the location for a key.[21]
histogram
A set of counters.[22]
implementation
A way of performing a computation.[23]
item
Another name for a key-value pair.[24]
key
An object that appears in a dictionary as the first part of a key-value pair.[25]
key-value pair
The representation of the mapping from a key to a value.[26]
lookup
A dictionary operation that takes a key and finds the corresponding value.[27]
nested loops
When there are one or more loops “inside” of another loop. The inner loop runs to completion each time the outer loop runs once.[28]
value
An object that appears in a dictionary as the second part of a key-value pair. This is more specific than our previous use of the word “value”.[29]

Review Questions

[edit | edit source]
Enable JavaScript to hide answers.
Click on a question to see the answer.
  1. A dictionary or associative array is _____.
    A dictionary or associative array is a data type composed of a collection of (key: value) pairs, such that each possible key appears at most once in the collection.
  2. Dictionary operations include:
    Dictionary operations include:
    the addition of a pair to the collection
    the removal of a pair from the collection
    the modification of an existing pair
    the lookup of a value associated with a particular key
  3. Dictionaries are typically implemented in programming languages as _____.
    Dictionaries are typically implemented in programming languages as either a hash table or a search tree.
  4. A hash table uses _____.
    A hash table uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found.
  5. A hash function is _____.
    A hash function is any function that can be used to map data of arbitrary size to data of fixed size.
  6. A good hash function should _____.
    A good hash function should map the expected inputs as evenly as possible over its output range.
  7. Python dictionaries are _____.
    Python dictionaries are collections that are indexed by keys, which can be any immutable type.
  8. It is best to think of a dictionary as _____.
    It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary).
  9. Placing a comma-separated list of key:value pairs within braces adds initial key:value pairs to the dictionary using the syntax _____.
    {{{2}}}
  10. A pair of braces creates an empty dictionary: {}. Dictionary items may be added, updated, and deleted by key using the syntax _____.
    {{{2}}}
  11. Dictionaries may be nested and are accessed using the syntax _____
    Dictionaries may be nested and are accessed using the syntax dictionary[key][subkey]
  12. Dictionary items may be accessed with a _____ loop.
    Dictionary items may be accessed with a for loop.
  13. Dictionaries are unordered. Dictionary items may be displayed in key order by _____.
    Dictionaries are unordered. Dictionary items may be displayed in key order by sorting a list of keys using the sorted() function and the dictionary.keys()method.
  14. Dictionaries are unordered. Dictionary items may be displayed in value order by _____.
    Dictionaries are unordered. Dictionary items may be displayed in value order by sorting a list of key-value pairs using the sorted() function and the dictionary.get() method.

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]