Python Tutorial-Dictionaries

Dictionaries are not really used in other programming languages, and are kind of hard to explain. In a sense a List is a dictionary in that you declare values in the list and each value has an index. You do not interact with the index unless you want to manipulate something in the list.

Dictionaries are similar to lists but include a key as well, so instead of Python assigning an index to each value in your list, you declare the key in your dictionary.

I hope that’s not too confusing but before I confuse you further let’s take a look.

Your output is {‘bananas’: 22, ‘apples’: 25, ‘strawberry’: 55}. What if I wanted to just show how many bananas I have?

Your output will be 22.

Now let’s suppose we wanted to add another item to our dictionary list of fruits. I am going to add 12 oranges to the dictionary (in this example it’s an inventory of fruit).

Your output is {‘apples’: 25, ‘bananas’: 22, ‘oranges’: 12, ‘strawberry’: 55}. Notice it did not append the oranges to the end but rather it placed the items in alphabetic order. However Python does not actually order them alphabetically. The dictionary list is actually not ordered.

One thing I have to caution you on is that you cannot create different values with the same key. Python will overwrite the value of the duplicate keys.

Let’s try vegetables now…

Your output should be:

green beans

Yes, I know tomatoes are not vegetables…sue me. We combined a for loop with dictionaries. Are you starting to see the power of Python yet? In this example Python only printed the keys. If we wanted to print the keys and values we would have to do the following:

Your output should be:

tomatoes 75
green beans 122
peppers 21
carrots 64
peas 454

Why would you want to use Dictionaries you ask? Well what if I needed to read a large data file, say IP addresses and sort them by how many times each IP address connected to a server? Now that I have put it into one real world scenario can you think of any other scenarios where something like this might be useful?

I would suggest getting some practice with dictionaries as it may seem a little confusing at first. Go ahead, ahve some fun and print out Webster’s Dictionary. Just’re not that crazy..or are you?