TYL P3- Dictionaries

max, min, sorted functions and dictionaries

For calculating maximum or minimum of a key based on value in dictionaries, use
max(d_obj, key = d_obj.get)

Try this out:
>>> d_income = {'Alice': 35000, 'Bob': 40000, 'Jenna': 55000}
>>> d_income
{'Alice': 35000, 'Bob': 40000, 'Jenna': 55000}
>>> max(d_income, key=d_income.get)
'Jenna'
>>> min(d_income, key=d_income.get)
'Alice‘
>>> sorted(d_income, key=d_income.get)
['Alice', 'Bob', 'Jenna']
>>> sorted(d_income, key=d_income.get, reverse=True)
['Jenna', 'Bob', 'Alice']min(d_obj, key = d_obj.get)

Question 1

For a supermarket, create 2 dictionaries called “stock” and “prices”.  
stock={‘raddish’:5,’apple’:2,’tomato’:5}
prices={‘raddish’:50, ‘apple’:100, ‘tomato’:30}
Create these two dictionaries using a list in the form [k1,k2,k3,k4,v1,v2,v3,v4] passed to this function.  
create(items_in_a_list), that creates a dictionary d={k1:v1,k2:v2,k3:v3, k4:v4} and returns a dictionary. ·         
display(), that displays key along with its price and stock information. 
compute_bill() that takes a list as an argument of all the items to be purchased, eg. [‘raddish’, ‘apple’]
Check if stock is greater than 0 for each item
Add the corresponding price of the item to a variable, ‘total’
Subtract 1 from the stock dictionary
Return total
 If_all_sold(), takes an argument and returns true if it is sold out
 max_stock(), that displays the product that is in maximum stock. 
max_price(), that displays the product with maximum price

How do we take a list, [k1,k2,k3, v1,v2,v3] into a dictionary?
We can use zip() that will take two are arguments, list of keys, list of values
We pass it to the dict() function and get a dictionary.

For display, try a bit of formatting.
remember if you did %20s, it will be right justified by default, add a - to change the default right justification for text to left justification
We pass a tuple to the formatted string before a %

eg. print("Player %s scores on 3 matches are  are %d %d and %d" % ('Anil', 45,50,48,50) )

Outline of the program:


Program: 
stock={}
prices={}

def create(lst):
    d={}
    # code to convert list of form
    #[k1,k2,k3,k4,v1,v2,v3,v4]
    #to dictionary k1:v1, k2:v2, ...

    num_keys = len(lst)//2
    key_list = lst[0:num_keys]
    value_list = lst[num_keys:]
    d= dict(zip(key_list,value_list)) 
        
    return d

def display():
    print("%-15s  %-10s %-10s" % ('Item', 'Stock','Price') )
    
    for key in stock:
        print("%-15s  %-10d Rs.%-10.2f" % (key, stock[key], prices[key]) )

def compute_bill(lst):
    total = 0.0

    # for each item in a list
    # if stock is>0
    # add the item's price to total
    # subtract 1 item from stock.

    for a in lst:
        if stock[a]>0:
            total+=prices[a]
            
        stock[a]-=1

    return total

def if_all_sold(item_name):
    # check if item is sold out
    # return yes or no
    if stock[item_name]>0:
        return "NO"
    else: return "YES"

def max_stock():
    #displays the product that is in maximum stock. 
    m_stock = max(stock, key = stock.get)
    print("Maximum stock item : ",m_stock)
    print("Stock: ", stock[m_stock])

def max_price():
    #displays the product with maximum price.
    m_price = max(prices, key = prices.get)
    print("Maximum price (item) : ",m_price)
    print("Price: Rs.", prices[m_price])


#Create dictionary Stock

print("\n   ** Creating stock and prices dictionary **  \n")
stock = create(['raddish','apple','tomato',5,2,10])
prices = create(['raddish','apple','tomato',50,100,30])


print("\n   ** Calling display() **  \n")
display()

purchase_list1 = ['raddish', 'apple']
purchase_list2 = ['tomato', 'apple']


print("\n   ** Calling compute_bill **  \n")
bill1 = compute_bill(purchase_list1)
bill2 = compute_bill(purchase_list2)

print("Purchasing", purchase_list1,"\n", "Bill: ", bill1)
print("Purchasing", purchase_list2,"\n", "Bill: ", bill2)


print("\n   ** if_all_sold **  \n")
print('Apple, Sold Out?',if_all_sold('apple') )
print('Raddish, Sold Out?',if_all_sold('raddish') )


print("\n   ** Max stock **  \n")
max_stock()

print("\n   ** Max price **  \n")
max_price()



Output:

python tyl_d.py

 ** Creating stock and prices dictionary **  


   ** Calling display() **  

Item             Stock      Price     
raddish          5          Rs.50.00     
apple            2          Rs.100.00    
tomato           10         Rs.30.00     

   ** Calling compute_bill **  

Purchasing ['raddish', 'apple'] 
 Bill:  150.0
Purchasing ['tomato', 'apple'] 
 Bill:  130.0

   ** if_all_sold **  

Apple, Sold Out? YES
Raddish, Sold Out? NO

   ** Max stock **  

Maximum stock item :  tomato
Stock:  9

   ** Max price **  

Maximum price (item) :  apple

Price: Rs. 100

Question 2

We represent scores of batsmen across a sequence of matches in a two level dictionary as follows: 
d = {'match1': {'player1':57, 'player2':38}, 
     'match2': {'player3':9, 'player1':42}, 
     'match3': {'player2':41, 'player4':63, 'player3':91} 
     }
Each match is identified by a string, as is each player. 
The scores are all integers. 
Define a Python function highestscore(d) that reads a dictionary d of this form and identifies the player with the highest total score. 

Your function should return a pair (playername, topscore) where playername is the name of the player with the highest score, and topscore is an integer, the total score of playername. 

The input will be such that there are never any ties for highest total score.

This is a good program to understand why returning a tuple is semantically better than a list or some other data type.


Program:


def highestscore(d):
    player_score={}
    for match,scores in d.items():
        for player,score in scores.items():
            player_score[player]=player_score.get(player,0)+score

    print(player_score)

    playername = max(player_score, key=player_score.get)
    highestscore = player_score[playername]
    return (playername,highestscore)


d = {
    'match1': {'player1':57, 'player2':38}, 
     'match2': {'player3':9, 'player1':42}, 
     'match3': {'player2':41, 'player4':63, 'player3':91} 
     }
playername,highestscore = highestscore(d)

print("Player with highest score:")
print(playername,":",highestscore)

Output:


python tyl_dict_match.py
{'player1': 99, 'player2': 79, 'player3': 100, 'player4': 63}
Player with highest score:
player3 : 100

Question 3


Given the following dictionary: 
inventory={‘gold’:500, 
                  'pouch' : ['flint', 'twine', 'gemstone'], 
                 'backpack' : ['xylophone','dagger', 'bedroll','bread loaf'] } 
Write a function ‘change(inventory)’, that returns the dictionary inventory{} after the following changes: 
Add a key to inventory called 'pocket'
Set the value of 'pocket' to be a list consisting of the strings 'seashell', 'strange berry', and 'lint'
Sort the items in the list stored under the key 'backpack'
Remove('dagger') from the list of items stored under the 'backpack' key. 
Add 50 to the number stored under the 'gold' key. 
Hint : You can use built-in functions.

Observe that inv and inventory are aliases.
The changes made in the dictionary inside the function are reflected in the dictionary outside the function.


Program:


def change(inv):
    
  #Add a key to inventory called 'pocket'
    inv['pocket']=None

    #Set the value of 'pocket' to be a list consisting of the
    #strings 'seashell', 'strange berry', and 'lint'.
    inv['pocket']=['seashell', 'strange berry','lint']
    
    #Sort the items in the list stored under the key 'backpack'.
    inv['backpack'] = sorted(inv['backpack'])

    #Remove('dagger') from the list of items stored under the 'backpack' key.
    inv['backpack'].remove('dagger')

    #Add 50 to the number stored under the 'gold' key.
    inv['gold']+=50

    
inventory={'gold':500, 
            'pouch' : ['flint', 'twine', 'gemstone'], 
            'backpack' : ['xylophone','dagger', 'bedroll','bread loaf'] } 


print(inventory)

change(inventory)

print('  ** After the change  **')
print(inventory)


Output:

python tyl_dict_inv.py 

{'gold': 500, 'pouch': ['flint', 'twine', 'gemstone'], 'backpack': ['xylophone', 'dagger', 'bedroll', 'bread loaf']}
  ** After the change  **
{'gold': 550, 'pouch': ['flint', 'twine', 'gemstone'], 'backpack': ['bedroll', 'bread loaf', 'xylophone'], 'pocket': ['seashell', 'strange berry', 'lint']}




    

Comments

Popular posts from this blog

TYL - Food Corner Program

Classes and objects solution

TYL - Salary Hike - Python Problem