Python Dictionaries

Teri MacLean
3 min readJan 15, 2022

--

I want to learn Python, so I’ve been working through the Automate the Boring Stuff book by Al Sweigart. I’m documenting my journey on Medium to help retain what I’ve learned and maybe help some of you as well! Check out what I’ve completed so far here:

Chapter 5 in Automate the Boring Stuff covers dictionaries. A dictionary is a data type that contains many values. This makes it similar to a list, but the similarity really ends there. Dictionaries are unordered and the indexes for dictionaries can use different data types.

Indexes in dictionaries are called key-value pairs. The index for a dictionary is the key, and the value is what the key refers to.

Dictionary

There are three dictionary methods that can be used to access the values within a dictionary: keys(), values(), and items(). The values returned by these methods cannot be altered or modified, but they can be iterated through with a ‘for loop’.

Using a for loop to iterate through data in a dictionary

The above is a very short and quick description of dictionaries. There are some more advanced features that can be used with dictionaries, but for my little practice projects shown below this was basically all I needed to know.

My first dictionary practice project in the book was to list inventory items and make them look nice. This one was fairly straightforward and didn’t take me too long to figure out. The problem example included everything except for what’s included in the for loop, so that’s all I had to sort out. The yellow squiggles are cautionary notices. It doesn’t like my lazy spacing. I’ll work on fixing that.

Dictionary practice problem code #1
Results for practice problem #1

The second practice problem was a bit trickier and it took me a bit longer to figure out. For this one, I had to see if the inventory item existed and if not add it to the list. If it did exist, I had to increment its value. This function took two arguments as well, one for the list and the other for the dictionary. Then I had to make it look pretty and add it all up like the previous problem.

I feel like there is probably a cleaner way to have done this, especially at the numbers part in the if statement but this worked for me.

Dictionary practice problem code #2
Results for practice problem #2

And that is chapter 5 in Automate the Boring Stuff. I’m excited to keep practicing, and can’t wait to get to the actual automation projects!

Up next, String Manipulation!

--

--

Teri MacLean

I’m a business analyst by day and an aspiring data analyst by night. Currently tackling SQL, Python, and creating vizzes.