TIL: Python Basics Day 9 - Dictionary

이다연·2020년 12월 2일
0

Udemy Python Course

목록 보기
9/64

Dictionary

{Key: Value}
Best Practive - formatting: next line, indent, comma at the end,

  • retreiving the item: dictionary has a key. dictionary["key"]
  • adding new items to dictionary: dictionary["new_word'] = "it will be added in the dictionary."
  • empty dictionary: empty_dictionary = {}
    can be used to wipe an existing dictionary:
  • Edit an item in a dictionary: can enter a new entry to change the value.
  • Loop through a dictionary: only key will be printed out, if you want keys and values printed out, code below will do so.
for key in programming_dictionary:
	print(key)
    print(programming_dictionary[key]) #-> retrieval code

Exercise 1. Grading Program

student_scores = {
  "Harry": 81,
  "Ron": 78,
  "Hermione": 99, 
  "Draco": 74,
  "Neville": 62,
}
# 🚨 Don't change the code above 👆

#TODO-1: Create an empty dictionary called student_grades.
student_grades = {}

#TODO-2: Write your code below to add the grades to student_grades.👇
for key in student_scores:
  if student_scores[key] >= 91:
    student_grades[key] = "Outstanding"
  elif student_scores[key] >= 81:
    student_grades[key] = "Exceeds Expectations"
  elif student_scores[key] >= 71:
    student_grades[key] = "Acceptable"
  else:
    student_grades[key] = "Fail"

# 🚨 Don't change the code below 👇
#print(student_scores)
print(student_grades)

using the correct data type is important.

*curly braces

Nesting

{
	key: [List],
    key2: {Dict},
}

Nested dictionary inside the dictionary

  • Accessed by its keys
travel_log = {
  "France": {"cities_visited": ["Paris", "Tour"], "total_visits": 2},
  "Germany": {"cities_visited": ["Berlin"], "total_visits": 1}
}
print(travel_log)

Nesting a dictionary inside a list

  • Inside the list, dictionaries are accessed by their index. First dictionary will be index 0, second index 1

Exercise 9.2 Dictionary in List

travel_log = [
  {"country": "France",  #-> datatype: string
   "cities_visited": ["Paris", "Tour"], #-> datatype: list
    "total_visits": 2}, #-> datatype: number

  {"country": "Germany", 
  "cities_visited": ["Berlin"],
   "total_visits": 1}
]

print(travel_log)
travel_log = [
{
  "country": "France",
  "visits": 12,
  "cities": ["Paris", "Lille", "Dijon"]
},
{
  "country": "Germany",
  "visits": 5,
  "cities": ["Berlin", "Hamburg", "Stuttgart"]
},
]
#🚨 Do NOT change the code above

#TODO: Write the function that will allow new countries
#to be added to the travel_log. 👇

#<my code>
def add_new_country(add_country, add_visits, add_cities):

  travel_log.append({
    "country": add_country,
    "visits": add_visits,
    "cities": add_cities
  })

#<Angela's code>
def add_new_country(country_visited, times_visited, cities_visited):
  new_country = {}
  new_country["country"] = country_visited
  new_country["visits"] = times_visited
  new_country["cities"] = cities_visited
  travel_log.append(new_country)




#🚨 Do not change the code below
add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
print(travel_log)

Exercise 9.3 Secret Auction

I searched how to get a max number in dictionary, however, Angela intended creating a function that loops through a dictionary.

from replit import clear

from art import logo
print(logo)

def finding_winner(bidders_info):
  highest_bidder = 0
  winner = ''
  for key in bidders_info:
    bidder_price = bidders_info[key] 
    if bidder_price > highest_bidder:
      highest_bidder = bidder_price
      winner = key
  print(logo)
  print(f"\n{winner} is a winner with a bid of ${highest_bidder}.")    
  

auction_finished = False
bidder_dict = {}
while not auction_finished:
  name = input("What is your name?: ")
  bid_amount = int(input("What's your bid?: $"))
  bidder_dict[name] = bid_amount


  other_bidders = input("Are there any other bidders? Type 'yes' or 'no' : ")
  if other_bidders == "yes":
    clear()
    print(logo)
  elif other_bidders == "no":
    clear()
    finding_winner(bidder_dict)
    auction_finished = True

logo = '''
                         ___________
                         \         /
                          )_______(
                          |"""""""|_.-._,.---------.,_.-._
                          |       | | |               | | ''-.
                          |       |_| |_             _| |_..-'
                          |_______| '-' `'---------'` '-'
                          )"""""""(
                         /_________\\
                       .-------------.
                      /_______________\\
'''   

#parameter "bidder_dict" is a generic name for any ditionary that will be used in the future
#dict bids is an example of a dictionary that will be assigned through fuction bid()
#We can get both winning bidder's name and amount by assigning highest amount bidder's name to winner variable after judging the amount.

bids = {
    "e": 212, 
    "d": 23
}

def bid(bidder_dict):
  highest_bidder = 0
  winner = ""
  for bidder in bidder_dict:
    bidder_price = bidder_dict[bidder] 
    if bidder_price > highest_bidder:
      highest_bidder = bidder_price
      winner = bidder 
  print(f"{winner} is a winner with a bid of ${highest_bidder}.")   
bid(bids)

https://www.kite.com/python/answers/how-to-find-the-max-value-in-a-dictionary-in-python

profile
Dayeon Lee | Django & Python Web Developer

0개의 댓글