HackerRank > Basic Data Types > Nested Lists
if __name__ == '__main__':
stu = dict()
for _ in range(int(input())):
name = input() # 처음 값은 name으로
score = float(input()) # 두번째 값은 score에 저장
stu[name] = score
# 입력 받은대로 stu 딕트에 넣어주기
second = sorted(set(stu.values()))[1]
# 두번째로 낮은 시험점수 찾기. 중복된 점수를 거르기 위해서 set에 넣어주었다. ascending이 디폴트이기 때문에 인덱스는 1
ans = []
for k, v in stu.items():
if v == second:
ans.append(k)
for x in sorted(ans):
print(x)
# 딕트 생성하기
today = {
"feeling" : "not bad",
"condition" : 5,
"food" : ["bread", "triangle rice"]
}
# key로 value 꺼내오기
print ( today["feeling"] )
print ( today.get("feeling") )
# not bad
# 아이템 갯수 세기
print ( len(today) )
# 딕트의 데이터 타입은
print ( type(today) )
# dict <class 'dict>
# constructor. 딕트를 생성 할 때 키는 ""안에 안넣어도 된다
furincess = dict( name="fubao", age = 2, food= ["bamboo", "apple"] )
# key들만 보기
print( furincess.keys() )
# dict_keys(['name', 'age', 'food'])
# value들만 보기
print( furincess.values() )
# dict_values(["fubao, 2, ["bamboo", "apple"]])
# item 추가하기
furincess["nickname"] = "푸릉지"
# item 리스트 불러오기
print(furincess.items())
# dict_items([('name', 'fubao'), ('age', 2), ('food', ['bamboo', 'apple'])])
# 키가 있는지 있는지 확인
if "food" in this dict:
print(True)
else:
print(False)
# True
# 밸류를 바꾸거나 업데이트 하기
furincess["year"] = 3
furincess.update({"year": 3})
print(furincess)
# {'name': 'fubao', 'age': 2, 'food': ['bamboo', 'apple']}
# 아이템 추가하기
furincess["home"] = "panda world"
furincess.update({"home" : "panda world"})
print(furincess)
# {'name': 'fubao', 'age': 3, 'food': ['bamboo', 'apple'], ''home': 'panda world'}
# 아이템 삭제하기
furincess.pop("home")
# panda world 밸류를 팝하고 삭제된다.
del furincess["home"]
print(furincess)
# {'name': 'fubao', 'age': 3, 'food': ['bamboo', 'apple']}
# 마지막에 추가한 아이템 삭제하기
furincess.popitem()
# ('food', ['bamboo', 'apple'])
print(furincess)
# {'name': 'fubao', 'age': 3}
# 딕셔너리 비우기. 존재는 있음
furincess.clear()
print(furincess)
# {}
# 딕셔너리 완전 삭제
del furincess
print(furincess)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# NameError: name 'furincess' is not defined
# 룹
## 키만 프린트
for x in furincess:
print(x)
for x in furincess.keys():
print(x)
# name
# age
# food
# 밸류만 프린트
for x in furincess:
print(furincess[x])
for x in furincess.values():
print(x)
# fubao
# 2
# ['bamboo', 'apple']
# 키와 아이템 모두 프린트
for k,v in furincess.items():
print(k,v)
# name fubao
# age 2
# food ['bamboo', 'apple']
# 딕셔너리 복사하기
fu = furincess.copy() # 깊은 복사
fuu = furincess # 얕은복사. 같은 메모리값을 가리키게 된다.
furincess["age"] = 3
print(fu)
# {'name': 'fubao', 'age': 2, 'food': ['bamboo', 'apple']}
print(fuu)
# {'name': 'fubao', 'age': 3, 'food': ['bamboo', 'apple']}
# Nested Dictionary
## 방법1
baos = {
"bao1" : {
"name" : "aibao",
"age" : 9,
},
"bao2" : {
"name" : "lebao",
"age" : 10,
},
"bao3" : {
"name" : "fubao",
"age" : 2,
}
}
## 방법 2
bao1 = {
"name" : "aibao",
"age" : 9,
}
bao2 = {
"name" : "lebao",
"age" : 10,
}
bao3 = {
"name" : "fubao",
"age" : 2,
}
baos = {
"bao1" : bao1,
"bao2" : bao2,
"bao3" : bao3
}
print(baos)
# {'bao1': {'name': 'aibao', 'age': 9}, 'bao2': {'name': 'lebao', 'age': 10}, 'bao3': {'name': 'fubao', 'age': 2}}
# nested dictionary에서 아이템 접근하기
print( baos["bao3"]["name"] )
# fubao
# 키가 존재하지 않을 경우, 아이템 추가
baos.setdefault("bao4", {"name":"gangbao"})
print(baos)
# {'bao1': {'name': 'aibao', 'age': 9}, 'bao2': {'name': 'lebao', 'age': 10}, 'bao3': {'name': 'fubao', 'age': 2}, 'bao4': {'name': 'gangbao'}}
# 키가 존재할 경우, 밸류 리턴
baos.setdefault("bao4", {"name":"songbao"})
# {'name': 'gangbao'}
3.7 이후로 딕셔너리는 정렬 된다. 이전 버전은 정렬 되지 않음
한 키에는 하나의 밸류만 저장 가능
밸류로 어떤 데이터 타입도 저장할 수 있다.
딕셔너리로 카피할 때는 dict2 = dict1 으로 복사 할 수 없다
method 정리