Small Python Program: Dictionaries
This small program was quite a challenge to figure out as it took me over at least an hour and a half to two hours to figure it out. As I was reading over dictionaries, I decided to create one on my own that will include a function. As you can see, I like functions… Dictionaries in my opinion, is similar to list except that this time you have keys and values. A great example of this is: {‘color’: ‘red’, ‘name’: ‘Tammy’, ‘place’: ‘Memphis’}
In this small program, the following is done:
Create a list with keys and values. I create a list of items that I have.
Sum the total of the values
Print out overall total and the key and value.
Below is my code:
myfav_items = {'dresses': 15, 'shoes': 26, 'purses': 12, 'hats': 5, 'earrings': 10}
def displayInventory(inventory): total = 0 for k, v in inventory.items(): print k, v total = total + inventory[k] print("Total number of items: " + str(total))
displayInventory(myfav_items) My results came out to be:
earrings 10 hats 5 shoes 26 dresses 15 purses 12 Total number of items: 68
*It is not the prettiest in formatting but just wanted to show how with the code abobe, each item and value can be displayed as well as the total.
Lesson Learned
One of the lessons I have learned throughout creating this program was the output of the keys and values, it took a while to figure how to do so but finally I took it step by step and worked from there. My code is not perfect but I like how it came out. Hopefully I get a chance to expand on if I wanted the user to input a key and a value for at least 5 things and then it gives the total.












