Skip to main content

Command Palette

Search for a command to run...

Mastering Python Dictionaries Data Structure

Published
2 min readView as Markdown
Mastering Python Dictionaries Data Structure

With a deep understanding of Python's dictionary data structure, we have to master and remember some of the fundamentals in creating a dictionary, allowing me to efficiently manipulate, organize, and analyze data through dynamic operations like adding a classes and objects.

For better understanding, I created all this python dictionaries provided by the activity posted in the portal.

First I created five dictionaries about Books, Employee, Restaurants, Universities, and Products.

For the Book Dictionary here is the result of the code:

For the Employee Dictionary:

Restaurant Dictionary:

University Dictionary:

And for the Product Dictionary:

Examples of Manipulating Dictionary:

Here is the code snippets for Product Dictionary that I will use as example

# Define the products dictionary

#Product Number One
product1 = {"name": "Laptop", 
            "price": 1200, 
            "quantity": 5
            }

#Product Number Two
product2 = {"name": "Monitor",
             "price": 300,
             "quantity": 8
            }

#Product Number Three
product3 = {"name": "Headphones",
             "price": 150,
             "quantity": 25
            }

#Product Number Four
product4 = {"name": "Keyboard",
            "price": 50,
            "quantity": 30
            }

#Product Number Five
product5 = {"name": "Mouse",
            "price": 30,
            "quantity": 15
            }   

allProduct = (product1, product2, product3, product4, product5)


for i, product in enumerate(allProduct):
    print(f"Product {i+1}: {product}")

In product dictionary, I change the price of the product number four

#Changing the price of product number four
product4["price"] = 70
print("\nUpdated Product 4:")
print(product4)

Here is the updated result of the product number four:

Accessing a classes inside an object: Here I tried to access the quantity of product number 5

#Accessing the quantity of product number five
print("\nQuantity of Product 5:", product5["quantity"])

Result:

And now I try to add another key for an object called MODEL

#Adding a model to the dictionary of products
product1["model"] = "Dell XPS 15"
product2["model"] = "Acer Nitro 5"
product3["model"] = "Sony WH-1000XM3"
product4["model"] = "Logitech G733"
product5["model"] = "Razer DeathAdder"

print("\nUpdated Products:")

for i, product in enumerate(allProduct):
    print(f"Product {i+1}: {product}")

And here is the result of new product dictionary

Github: https://github.com/rodney-lqr/MasterPythonDictionaries

More from this blog