Python Training – Python Dictionaries

If you just landed here looking start Python studies, it is recommended you start out with my previous post on introduction to Python programming. That should be enough to get you up and running. If for some reason you find it lacking, just shoot me a message and I’ll be sure to make clarifications. Otherwise, if you landed here just looking to learn more about Python dictionaries, then read on!

If you find any of these lessons compelling, and are looking for Python training, do reach out. I’ve authored several courses on Python programming, and would love to be the trainer for your next corporate event, be that onsite or online. If you need a quote, I’m only an email away.

Dictionaries are all about key:value pairs. The key always points to the value, but the value does not point to the key. At first you might think this is kind of silly, but it’s actually quite useful, especially when paired with a list.

webster01.py

Lab 2.1 – Dictionaries Python

#!/usr/bin/python3
# the line above here is called a 'shebang'
# it is best practice, you should always write it in

# create a dictionary with mustache brackets
statecap = { "PA": "Harrisburg", "NY": "Albany" }

# display the content of statecap
print(statecap)

# print the value associated with the key "PA"
print(statecap["PA"])

# print the value associated with the key "NY"
print(statecap["NY"])

# add another key:value pair to the dictionary
statecap["IA"] = "Des Moines"

# display the new content of statecap
print(statecap)

# print just the value associated with "IA"
print(statecap["IA"])

# display all the capitals
print("All the state capitals in the data base are: ")
# use a dictionary METHOD to display all of the keys in the dictionary
print(statecap.keys())

# pause the program until ENTER is pressed
input("Press ENTER to exit.")

Save then run your script.

If anything needs explaining in the previous script, it is the statecap.keys(). The shortest explanation of a method, is that it is a function written inside of a class. A function is easy enough. It’s just a block of code that is run when the function is called. Python has a bunch of them built-in. You can check them out here: Python Built-in Functions. You can also define your own functions, which is quite useful when you have repetitious code you want to continually call.

So what is a class? The class analogy is that a class is a factory for creating objects. The Nissan factory (class) makes Maxima (objects). The Maximas produced at the factory are not all exactly the same, but they’re share a lot of the same common characteristics. The same could be said about the dict class, which creates dictionary objects. Let’s play with this idea in the next script.

webster02.py

Lab 2.2 – Reveal an object type

#!/usr/bin/python3
# the line above here is called a 'shebang'
# it is best practice, you should always write it in

# create an dictionary with mustache brackets
movies = {"Alien": "Ridley Scott", "Avatar": "James Cameron"}

# use the built in type function to reveal the type of object
print(type(movies))

# use the built in dir function to reveal the names in this dict object
print(dir(movies))

# print a blank line
print()

# create a string
arnold = "I'll be back"

# use the built in type function to reveal the type of the object
print(type(arnold))

# use the built in dir function to reveal the names in this str object
print(dir(arnold))

Save and run your code.

The first line on the screen reveals that movies was created from the class ‘dict’. After that should be a big list of words separated by commas.

In short, we are displaying all of the ‘names’ inside of dictionary. It’s kind of like the DNA of a dictionary. The results would be the same no matter what dictionary you ran this experiment on. For the foreseeable future, ignore all of the stuff with __underlines__ around it. Everything that’s left, are more than likely methods. You should get to know as many as you can. You can learn how to use them by reviewing the Python documentation. The official documentation could be friendlier to newcomers, but simple descriptions of the methods available to dictionary objects can be found here Python.org documentation on dictionaries

As aforementioned, methods are functions defined within a class. Notice there is one called, ‘keys’. You used it previously to return all of the keys from the dictionary statecap.

The next output reveals that the object arnold is a string created from the class ‘str’. What follows are methods unique to objects from the string class. Notice that they’re not exactly the same as the methods associated with dictionaries! You’ll find most methods are tied to a single class.

webster03.py

Lab 2.3 – Dictionaries and Methods

#!/usr/bin/python3
# intro to storing data in lists

# create a dictionary of the vendors in our network
netvendors = {"campus_east": "cisco", "campus_west": "juniper", "campus_northeast": "cisco"}

# display some information about our network
# print the string "The number of campuses:" followed by
# the result of using builtin len() function on netvendors dict
print("The number of campuses: ", len(netvendors))

# display the vendors used in the network
# by displaying the values associated with our keys
print("The vendors used in the network: ", netvendors.keys())

# If you wanted to eliminate the doubles, you can create a set()
# a set() is a collection of unique items
print("The vendors used in the network: ", set(netvendors.keys()))

# might as well introduce a for-loop as well
# a for-loop is a way to step through a collection
# the format is for  in :
# in python if a line ends with a : you should always indent the next line
# 4 whitespaces is best practice
# when you loop through a dictionary, the key is always returned
for vendor in netvendors:
    print("On the campus", vendor, "the network vendor", netvendors[vendor], "is used.")

# define a new dictionary of campuses and vendors
southAmerica_campuses = {"campus_brazil": "arista", "campus_chile": "cisco"}

# combine our two dictionaries
# the update method makes this easy
netvendors.update(southAmerica_campuses)

# show the new single dict
print(netvendors)
 

Save and run your code.

If you have any questions about the exercises above, be sure to post them below. I’ll do my best to follow up with any clarifications, and update this article from time to time to link to other blog posts I make concerning relevant Python training.

If you did enjoy this lesson, or ended up here because you need python training solution for a large group, I am a full-time author and instructor for automating with Python and Ansible. I had my start in telecom, but my passion has always been coding. So if you need a quote, use my website to shoot me an correspondence. Alternatively, in some small attempt to defeat the spambots, I typically hide my email address within the silly Python-snake images I make for these posts.

Happy python programming!

Previous
Previous

Python Training – Making choices with if, elif, else

Next
Next

Introduction to Python Programming