[udemy] python 부트캠프 _ section 9_딕셔너리, 네스팅 및 시크릿 옵션

Dreamer ·2022년 8월 17일
0
post-thumbnail

01. 딕셔너리

  • 관련된 정보들을 몇 개의 그룹으로 묶어줄 수 있음.

  • key : 단어 / value : 정의

  • {key : value}

programming_dictionary = {
  "Bug": "An error in a program that prevents the program from running as expected.", 
  "Function": "A piece of code that you can easily call over and over again."
}
  • 중괄호 / 각 값마다 들여쓰기!
  • 딕셔너리에서 value값을 불러오려면 key 값 입력
  • 정확한 key 명을 쓰지 않으면 keyerror 발생
  • key 값이 문자형이라면 정확히 "" 작성 후 불러올 것.
print(programming_dictionary["Bug"])
  • Adding new items to dictionary.
programming_dictionary["Loop"] = "The action of doing something over and over again."
  • Create an empty dictionary
empty_dictionary = {} 
  • Wipe and existing dictionary
programming_dictionary = {}
print(programming_dictionary)
  • Edit an item in a dictionary
programming_dictionary["Bug"] = "A moth in your computer."
  • Loop through a dictionary
for thing in programming dictionary:
   print(thing)
  • 위와 같이 출력하면 그냥 key만을 출력함.
  • value도 함께 출력하고 싶다면 다음과 같이 작성
print(programming_dictionary[Key])

02. quiz

student_scores = {
  "Harry": 81,
  "Ron": 78,
  "Hermione": 99, 
  "Draco": 74,
  "Neville": 62,
}

student_grades = {}

for key in student_scores:
  score = student_scores[key]
  if score > 90: 
    student_grades[key] = "Outstanding"
  elif score > 80 :
    student_grades[key] = "Exceeds Expectations"
  elif score > 70 :
    student_grades[key] = "Acceptable"
  else:
    student_grades[key] = "Fail"
    
print(student_grades)

03. 리스트와 딕셔너리 중첩하기

  • {Key : [List] , Key2 : {Dict}}
  • Nesting
#Nesting 
capitals = {
  "France": "Paris",
  "Germany": "Berlin",
}
  • Nesting a List in a Dictionary
travel_log = {
  "France": ["Paris", "Lille", "Dijon"],
  "Germany": ["Berlin", "Hamburg", "Stuttgart"],
}
  • Nesting Dictionary in a Dictionary
travel_log = {
  "France": {"cities_visited": ["Paris", "Lille", "Dijon"], "total_visits": 12},
  "Germany": {"cities_visited": ["Berlin", "Hamburg", "Stuttgart"], "total_visits": 5},
}
  • Nesting Dictionaries in Lists
travel_log = [
{
  "country": "France", 
  "cities_visited": ["Paris", "Lille", "Dijon"], 
  "total_visits": 12,
},
{
  "country": "Germany",
  "cities_visited": ["Berlin", "Hamburg", "Stuttgart"],
  "total_visits": 5,
},
]

04. quiz

travel_log = [
{
  "country": "France",
  "visits": 12,
  "cities": ["Paris", "Lille", "Dijon"]
},
{
  "country": "Germany",
  "visits": 5,
  "cities": ["Berlin", "Hamburg", "Stuttgart"]
},
]

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)

add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
print(travel_log)

05. quiz

from replit import clear
from art import logo

print(logo)

dic = {}
bid_continue = True

while bid_continue:
  name = input("What is your name?: ")
  bid_price = int(input("What is your bid?: $"))
  dic[name] = bid_price
  ans = input("Are there any other bidders? 'yes' or 'no'.: ").lower()
  if ans == "yes":
    clear() 
  elif ans == "no":
    bid_continue = False
    max_bid = max(dic.values())
    winner = max(dic, key = dic.get)
    print(f"The winner is {winner},the bid is ${max_bid}.")
  else:
    print("You put wrong answer.")
from replit import clear
from art import logo
print(logo)

bids = {}
bidding_finished = False

def find_highest_bidder(bidding_record):
  highest_bid = 0
  winner = ""
  # bidding_record = {"Angela": 123, "James": 321}
  for bidder in bidding_record:
    bid_amount = bidding_record[bidder]
    if bid_amount > highest_bid: 
      highest_bid = bid_amount
      winner = bidder
  print(f"The winner is {winner} with a bid of ${highest_bid}")

while not bidding_finished:
  name = input("What is your name?: ")
  price = int(input("What is your bid?: $"))
  bids[name] = price
  should_continue = input("Are there any other bidders? Type 'yes or 'no'.\n")
  if should_continue == "no":
    bidding_finished = True
    find_highest_bidder(bids)
  elif should_continue == "yes":
    clear()
  

  • 한 가지 문제를 해결하는 데 여러가지 방법이 존재한다는 것이 코딩의 가장 큰 매력이 아닐까 싶다.
profile
To be a changer who can overturn world

0개의 댓글