Dictionary (Python)

DICTIONARY

1. Repeatedly ask the user to enter a team name and how many games the team has won and how many they lost. Store this information in a dictionary where the keys are the team names and the values are the lists of the form [wins, losses].
(a) Using the dictionary created above, allow the user to enter a team name and print out the teams winning percentage.
(b) Using the dictionary, create a list whose entries are the number of wins of each team.
(c) Using the dictionary, create a list of all those teams that have winning records.

team_dict ={}
winningList=[]
winningTeam=[]

numofTeams=int(input("Insert Number of Teams: "))

for x in range(numofTeams):
 teamName=input('Team Name: ')
 winLossList=[]
 wins = int(input('Wins: '))
 winningList.append(wins)
 losses=int(input('Losses: '))
 if(wins>losses):
  winningTeam.append(teamName)
 
 winLossList.append(wins)
 winLossList.append(losses)
 team_dict[teamName] = winLossList

print("\nEntered dictionary: ", team_dict)
print('List of wins of all teams: ', winningList)
print("List of all teams that have winning records: ", winningTeam)


while True:
 
 team=input("\nEnter a team name to know the winning percentage: ")
 if team in team_dict:
  total_number_of_matches=sum(team_dict[team])        
  print('Total Number of Matches played by ', team,' : ', total_number_of_matches)
  winsVsLoss=team_dict[team]             
  winning_percentage=(float(winsVsLoss[0])/float(total_number_of_matches))*100 
  print("Winning percentage of ",team," : ","{0:.2f}".format(winning_percentage),"%")
 else:
  print("the key doesnt exist")
2. Write a program that repeatedly asks the user to enter product names and prices. Store all of these in dictionary whose keys are the product names and whose values are the prices. When the user is done entering products and prices, allow them to repeatedly enter a product name and print the corresponding price or a message if the product is not in the dictionary.
my_dict ={}
numberOfProducts=int(input('Enter Number of products: '))
for x in range(numberOfProducts):
 productName=input('Product Name: ')
 PriceOfProduct = int(input('Price: '))
 my_dict[productName] = PriceOfProduct

print(my_dict)

while True:
 productName=input('\nEnter a product name to know its price: ')
 if productName in my_dict:
  print('The price of ',productName, ' is ',my_dict[productName],' rupees.')
 else:
  print("The product you have entered doesn't exist")
3. Create a dictionary whose keys are month names and whose values are the number of days in the corresponding months.a. Ask the user to enter month name and use the dictionary to tell how many days are in the month.
b. Print out all the keys in alphabetical order.
c. Print out all of the months with 31 days
d. Print out the (key-value) pairs sorted by the number of days in each month.
Calendar2018 = {
'january' : 31,
'february' : 28,
'march' : 31,
'april' : 30,
'may' : 31,
'june' : 30,
'july' : 31,
'august' : 31,
'september' : 30,
'october' : 31,
'november' : 30,
'december' : 31
}

monthName=str(input("Please enter a month name: "))
monthName=monthName.lower()

if monthName in Calendar2018:
 print('\nThe month ',monthName,' has ',Calendar2018[monthName],'days\n')
else:
 print("the month doesnt exist")

sortedkeys = sorted(Calendar2018)
print('\nThe months in alphabetical order:\n')
for i in sortedkeys:
 print(i)

print("\nAll months with 31 days are as under: \n")
for month in Calendar2018:
 if Calendar2018[month]==31:
  print(month)

sortedByValues=sorted(Calendar2018.items(), key=lambda x: x[1])

print("\nThe (key-value) pairs sorted by the number of days in each month are as under.\n")

for i in range(len(sortedByValues)):
 print(sortedByValues[i])        
4. Can you store the details of 10 students in a dictionary at the same time? Details include-roll numbers, marks, grade etc. Give example to support your answer.
Answer: Yes we can we use nested dictionary for that
StudentsData={}              
numOfStudents=int(input('Insert the number of Students: '))
print("\n")
for x in range(numOfStudents):
 name=input('Student Name? ')
 StudentsData[name]={}           
 StudentsData[name]['TotalMarks']=input('Total Marks? ')   
 StudentsData[name]['RollNumber']=input('Roll Number? ')   
 StudentsData[name]['Grade']=input('Grade? ')     
 print("\n")
 
print("\nDictionary: ",StudentsData,"\n")          

for key in StudentsData:
 print("Student Name",key,':')
 print("Total Marks:",str(StudentsData[key]['TotalMarks']))
 print("Roll Number:",str(StudentsData[key]['RollNumber']))
 print("Grade   :",str(StudentsData[key]['Grade']))
 print("\n")        
5. Given the dictionary x = { 'k1' : 'v1', 'k2' : 'v2' : 'k3' : 'v3'}, create a dictionary with the opposite mapping i.e., write a program to create the dictionary as:
inverted_x = {'v1' : 'k1' , 'v2' : 'k2' , 'v3' : 'k3'}

x = { 'k1' : 'v1', 'k2' : 'v2', 'k3' : 'v3'}
print(" Given Dictionary: ", x)
inverted_x = {v: k for k, v in x.items()}
print("Inversed Dictionary ", inverted_x)        
6. Given two dictionaries say D1 and D2. Write a program that lists the overlapping keys of the dictionaries, i.e., if a key of D1 is also a key of D2, then list it.
D1 = {'miko': 'chan','caitlyn':14,'jack':22,'john':'doe'}
D2 = {'john': 'cena','caitlyn':'snow','jack':25}
print("Dictionary D1: ", D1)
print("Dictionary D2: ", D2)
print("\nThe ovelapping keys are: \n")

for key in list(D1.keys()):
    if key in list(D2.keys()):
        print(key)        
7. Write a program that checks if two same values in a dictionary have different keys. That is if dictionary D1={'a':10,'b':20,'c':10}, the program should print "2 keys have same values" and if dictionary D2={'a':10,'b':20,'c':30} , the program should print "No keys have same values"
d1={'a':10,'b':20,'c':10}
i=0
print("Dictionary: ", d1)

for key1 in  d1:
 for key2 in d1:
  if key1==key2:
   continue
  if d1[key1]==d1[key2]:
   i=i+1
if(i==0):
 print("No keys have same values")
else:   
 print(i," keys have same values")

j=0
d2={'a':10,'b':20,'c':30}   
print("Dictionary: ", d2)

for key1 in  d2:
 for key2 in d2:
  if key1==key2:
   continue
  if d2[key1]==d2[key2]:
   i=i+1
if(i==0):
 print("No keys have same values")
else:   
 print(i," keys have same values")        

Comments

Popular posts from this blog

Chapter 05 - File Handling

Tuple (Python)