• Understanding Data Sorting and Types in Python - Part 3

    Creating and using a dictionary


    Creating and using a dictionary is much like working with a list, except that you must now define a key and value pair. Here are the special rules for creating a key:

     The key must be unique. When you enter a duplicate key, the information found in the second entry wins — the first entry is simply replaced with the second.

     The key must be immutable. This rule means that you can use strings, numbers, or tuples for the key. You can’t, however, use a list for a key.

    You have no restrictions on the values you provide. A value can be any Python object, so you can use a dictionary to access an employee record or other complex data. The following steps help you understand how to use dictionaries better.


     Open a Python Shell window.

    You see the familiar Python prompt.

     Type Colors = {“Sam”: “Blue”, “Amy”: “Red”, “Sarah”: “Yellow”} and press Enter.

    Python creates a dictionary containing three entries with people’s favorite colors. Notice how you create the key and value pair. The key comes first, followed by a colon and then the value. Each entry is separated by a comma.

     Type Colors and press Enter.

    You see the key and value pairs. However, notice that the entries are sorted in key order. A dictionary automatically keeps the keys sorted to make access faster, which means that you get fast


    search times even when working with a large data set. The downside is that creating the dictionary takes longer than using something like a list because the computer is busy sorting the entries.


     Type Colors[“Sarah”] and press Enter.

    You see the color associated with Sarah, Yellow. Using a string as a key, rather than using a numeric index, makes the code easier to read and makes it self-documenting to an extent. By making your code more readable, dictionaries save you considerable time in the long run (which is why they’re so popular). However, the convenience of a dictionary comes at the cost of additional creation time and a higher use of resources, so you have trade-offs to consider.



     Type Colors.keys( ) and press Enter.

    The dictionary presents a list of the keys it contains. You can use these keys to automate access to the dictionary.


     Type the following code (pressing Enter after each line and pressing Enter twice after the last line):

    for Item in Colors.keys(): print("{0} likes the color {1}."
    .format(Item, Colors[Item]))

    The example code outputs a listing of each of the user names and the user’s favorite color. Using dictionaries can make creating useful output a lot easier. The use of a meaningful key means that the key can easily be part of the output.


     Type Colors[“Sarah”] = “Purple” and press Enter.

    The dictionary content is updated so that Sarah now likes Purple instead of Yellow.

     Type Colors.update({“Harry”: “Orange”}) and press Enter. A new entry is added to the dictionary.

     Place your cursor at the end of the third line of the code you typed in Step 6 and press Enter.

    The editor creates a copy of the code for you. This is a time-saving technique that you can use in the Python Shell when you experiment while using code that takes a while to type. Even though you have to type it the first time, you have no good reason to type it the second time.

     Press Enter twice.

    You see the updated output. Notice that Harry is added in sorted order. In addition, Sarah’s entry is changed to the color Purple.


     Type del Colors[“Sam”] and press Enter.

    Python removes Sam’s entry from the dictionary.

     Repeat Steps 9 and 10.

    You verify that Sam’s entry is actually gone.

     Type len(Colors) and press Enter.

    The output value of 3 verifies that the dictionary contains only three entries now, rather than 4.

     Type Colors.clear( ) and press Enter.

     Type len(Colors) and press Enter.

    Python reports that Colors has 0 entries, so the dictionary is now empty.

     Close the Python Shell window.


    Replacing the switch statement with a dictionary

    Most programming languages provide some sort of switch statement. A switch statement provides for elegant menu type selections. The user has a number of options but is allowed to choose only one of them. The program takes some course of action based on the user selection. Here is some representative code (it won’t execute) of a switch statement you might find in another language:


    switch(n)
    {
    case 0:
    print("You selected blue."); break;
    case 1:
    print("You selected yellow."); break;
    case 2:
    print("You selected green."); break;
    }

    The application normally presents a menu-type interface, obtains the number of the selection from the user, and then chooses the correct course of action from the switch statement. It’s straightforward and much neater than using a series of if statements to accomplish the same task.

    Unfortunately, Python doesn’t come with a switch statement. The best you can hope to do is use an if...elif statement for the task. However, by using a dictionary, you can simulate the use of a switch statement. The following steps help you create an example that will demonstrate the required technique.

     Open a Python File window.

    You see an editor in which you can type the example code.

     Type the following code into the window — pressing Enter after each line:

    def PrintBlue():
    print("You chose blue!\r\n")

    def PrintRed():
    print("You chose red!\r\n")

    def PrintOrange():
    print("You chose orange!\r\n")

    def PrintYellow():
    print("You chose yellow!\r\n")

    Before the code can do anything for you, you must define the tasks. Each of these functions defines a task associated with selecting a color option onscreen. Only one of them gets called at any given time.

     Type the following code into the window — pressing Enter after each line:

    ColorSelect = {
     PrintBlue,
     PrintRed,
     PrintOrange,
     PrintYellow
    }

    This code is the dictionary. Each key is like the case part of the switch statement. The values specify what to do. In other words, this is the switch structure. The functions that you created earlier are the action part of the switch — the part that goes between the case statement and the break clause.


     Type the following code into the window — pressing Enter after each line:

    Selection = 0

    while (Selection != 4): print("0. Blue") print("1. Red") print("2. Orange") print("3. Yellow") print("4. Quit")

    Selection = int(input("Select a color option: "))

    if (Selection >= 0) and (Selection < 4): ColorSelect[Selection]()

    Finally, you see the user interface part of the example. The code begins by creating an input variable, Selection. It then goes into a loop until the user enters a value of 4.

    During each loop, the application displays a list of options and then waits for user input. When the user does provide input, the application performs a range check on it. Any value between 0 and 3 selects one of the functions defined earlier using the dictionary as the switching mechanism.

     Choose RunRun Module.

    You see a Python Shell window open. The application displays a menu like the one.



     Type 0 and press Enter.

    The application tells you that you selected blue and then displays the menu again, as.


     Type 4 and press Enter.

    The application ends.


    Creating Stacks Using Lists


    A stack is a handy programming structure because you can use it to save an application execution environment (the state of variables and other attributes of the application environment at any given time) or as a means of determining an order of execution. Unfortunately, Python doesn’t provide

    a stack as a collection. However, it does provide lists, and you can use a list as a perfectly acceptable stack. The following steps help you create an example of using a list as a stack.

     Open a Python File window.

    You see an editor in which you can type the example code.

     Type the following code into the window — pressing Enter after each line:

    MyStack = []
    StackSize = 3

    def DisplayStack():

    print("Stack currently contains:") for Item in MyStack:
    print(Item)

    def Push(Value):

    if len(MyStack) < StackSize: MyStack.append(Value)
    else:
    print("Stack is full!")

    def Pop():

    if len(MyStack) > 0: MyStack.pop()
    else:
    print("Stack is empty.")

    Push(1)
    Push(2)
    Push(3)
    DisplayStack()
    input("Press any key when ready...")

    Push(4)
    DisplayStack()
    input("Press any key when ready...")

    Pop()
    DisplayStack()
    input("Press any key when ready...")

    Pop()
    Pop()
    Pop()
    DisplayStack()


    In this example, the application creates a list and a variable to determine the maximum stack size. Stacks normally have a specific size range. This is admittedly a really small stack, but it serves well for the example’s needs.

    Stacks work by pushing a value onto the top of the stack and popping values back off the top of the stack. The Push() and Pop() functions perform these two tasks. The code adds DisplayStack() to make it easier to see the stack content as needed.

    The remaining code exercises the stack (demonstrates its functionality) by pushing values onto it and then removing them. There are four main exercise sections that test stack functionality.

     Choose RunRun Module.

    You see a Python Shell window open. The application fills the stack with information and then displays it onscreen. In this case, 3 is at the top of the stack because it’s the last value added.


     Press Enter.

    The application attempts to push another value onto the stack. However, the stack is full, so the task fails.

     Press Enter.

    The application pops a value from the top of the stack. Remember that 3 is the top of the stack, so that’s the value that is missing.


     Press Enter.

    The application tries to pop more values from the stack than it contains, resulting in an error. Any stack implementation that you create must be able to detect both overflows (too many entries) and underflows (too few entries).



  • 0 comments:

    Post a Comment

    Powered by Blogger.

    Tags

    Popular Posts