Python Classroom Series – 07/Mar/2020

Dictionaries in Python

  • Dictionary structure organizes data in the format of

    • key value pairs
  • Dictionary can be declared by using

my_dict = dict()

other_dict = {}
  • Product information was stored in list using
product = [1,'dell', 'lattitude', 30000, 40000, 10]

# to access name
product[1] 

# to change quantity
product[5] = 20
  • Same product can be stored in very much readable way using dictionaries
product = { 'id': 1, 'name': 'dell', 'model': 'lattitude', 'costprice': 30000, 'sellingprice': 40000, 'quantity': 10}

# to access name
product['name']

# to change quantity
product['quantity'] = 20
  • Now the POS (Point of Sales) from previous classroom notes with dictionary implementation will look like
menu = """
Enter the number 
0 => View Products
1 => Add Product
2 => Update Product
3 => Delete Product
4 => Sell Items
5 => Report
6 => Exit
"""
# structure of dictionary will be
# {
#   '<code>' :  {
#        'name': '<product name>',
#        'quantity': <product quantity> 
#   }  
# }

# example:
#  products = {
#      'dell': { 'name': 'dell', 'cp': 30000, 'sp': 34000, 'quantity': 20, 'model': 'latitude'},
#      'hp': { 'name': 'hp', 'cp': 30000, 'sp': 34000, 'quantity': 20, 'model': 'elitebook'},
# }
products = {}

while True:
    choice = input(menu)
    if choice == '0':
        for code, product in products.items():
            print(f"{code} = {product}")
    elif choice == '1':
        code = input('Enter the product code name = ')
        if code in products:
            print(f'{code} already exists')
            continue
        product = {}
        product['name'] = input('Enter the product name = ')
        product['model'] = input('Enter the model = ')
        product['cp'] = float(input('Enter the cost price = '))
        product['sp'] = float(input('Enter the sell price = '))
        product['quantity'] = int(input('Enter the availablie quantity = '))
        products[code] = product
    elif choice == '2':
        code = input('Enter the product code name = ')
        if code not in products.keys():
            print('Invalid code entered. Please check the code')
            continue
        quantity = int(input('Enter the quantity to be added ='))
        new_quantity = quantity + products[code]['quantity']
        products[code]['quantity'] = new_quantity
        print(f'quantity updated and new quantity is {new_quantity}')
    elif choice == '3':
        code = input('Enter the product code name = ')
        if code not in products.keys():
            print('Invalid code entered. Please check the code')
            continue
        return_product = products.pop(code)
        print(f"{return_product} has been deleted")
    else:

        exit(0)

Python Sets

  • Representation of Mathematical Sets can be done in python
set_a = {1,2,3}
set_b = {3,4,5}
set_c = {2,3}
  • try following
set_a.union(set_b)
set_a.difference(set_b)
set_a.intersection(set_c)
set_a.issuperset(set_b) # false
set_a.issuperset(set_c) # true

Splitting and Joining Strings

  • Split the strings into list of strings
csv_record = "1, dell, lattitude, 30000, 35000,10"
csv_record.split(',')

  • Joining list of strings into one string
items = ["dell ", "hp ", "acer"]
message = ""
message.join(items)
  • Split the path directories into list of strings
import os
# get path value from environmental variables

path_text = os.getenv('PATH')
paths = path_text.split(';')
for path in paths:
    # check if path exists
    print(path)

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin