본문 바로가기

Python 🎧

[python] 딕셔너리 - 호출/추가/편집/지우기/리스트/중첩

☃︎ 딕셔너리 기본 사용법

#딕셔너리 {key : value}
dic = {"나" : "배고픈 사람",
       "너" : "배고플 사람"}

# 키를 써서 부를 수 있음
print(dic["나"])

# 딕셔너리 추가방법
dic["얘"] = "배고팠던 사람"
print(dic["얘"])

#딕셔너리 편집
dic["너"] = "배고플 예정인 사람"
print(dic["너"])

# 딕셔러리 전체 출력
for key in dic :
  print(key + " : " +dic[key])

# 딕셔너리 지우는 방법
dic = {}
print(dic)

 

실행결과

 

 

☃︎ 등급 판별기

score = {"홍길동" : 100,
         "김민수" : 70,
         "박명수" : 40
         }

def grade(sc) :
  result = ""
  if sc >= 90 :
    result = "A"
  elif sc >= 80 :
    result = "B"
  elif sc >= 70 :
    result = "C"
  elif sc >= 60 :
    result = "D"
  else :
    result = "F"

  return result

for key in score :
  print(f"{key} : {grade(score[key])}")

 

실행결과

 

☃︎ 리스트와 딕셔너리 중첩 

# 리스트와 딕셔너리 중첩 {key : [list], key2 : {dict}}
travel_log = [
    {
        "country" : "france"  ,
        "cities_visited" : ["paris", "lille", "dijon"],
        "total_visits" : 12 
    },
    {
        "country" : "germay" , 
        "cities_visited" : ["berlin", "hamburg","stuttgart"], 
        "total_visits" : 5
    }
]

def add_new_country(country,cities_visited,total_visits) :
  new_country = {}
  new_country["country"] = country
  new_country["cities_visited"] = cities_visited
  new_country["total_visits"] = total_visits

  travel_log.append(new_country)

ct = input("나라 이름 : ")
cities = []
for i in range(1,4) :
  cities.append(input(f"도시명{i} : "))
tv = input("방문 수 : ")

add_new_country(ct, cities, tv)

print(travel_log)

 

실행결과