Extracting and printing specific items from a dictionary in Python could be a nightmare. You may want to print only the values or keys. Maybe you want to print both in one report or what could you do if you are adding additional information such as units?
Let’s say you have a dictionary with a list of resources that you will need to prepare different types of coffee. After each order, you would like to receive an updated report of the quantity of ingredients remaining. The dictionary looks like this:

The report should have not only the ingredient name (key) and quantity (value), but also specific units for each ingredient, something that was not added to the original dictionary. This is an example of the report:

I knew that to access each element in the dictionary I had to use a for loop. I also used the .items( ) function to access both, the key and the value, and iterate with both items at the same time. Here is the code I wrote and the result:
Input: for loop and .items( ) function:

Output:

I had my report with the ingredients and quantities but without units. So I decided to make a new dictionary using the same key as the dictionary called: resources, but with the units as values. After that, I created a new variable called: unit that iterated with the units dictionary and stored the value each time the for loop was executed:
Input: dictionary “units” and new variable “unit”

Output:

As you can see in the final result, the report contains the ingredient, quantity and unit for each line. Here is more information about the .items() function:
.items( ) function
The .items()
method in a dictionary is highly useful for accessing both the keys and values simultaneously. When called on a dictionary, it returns a view object that displays a list of the dictionary’s key-value tuple pairs. This is particularly beneficial in loops where you need to iterate through all items in the dictionary. By using .items()
, you can efficiently process or manipulate each key-value pair without needing to separately access keys and values. This leads to more concise and readable code, especially when performing tasks like updating values, formatting outputs, or combining data from multiple dictionaries.
Leave a Reply