Python공부

Python - Dictionary(딕셔너리)_ get,[ ]의 차이

SoSweetStrawberry 2022. 8. 16. 22:34
반응형

 

1. 딕셔너리 생성

2. 딕셔너리 사용 ( 추가, 삭제, 추출)

3. 모든 Key or Value 추출_for문 이용

4.  type()  is ~ 사용하기

-----------------------------------------------------------------------------------------------------------------------------------------------

목록 선언 -> [ ]

딕셔너리 선언 -> { }   /    접근 -> dic [ 'Key' ]

-------------------------------------------------------<딕셔너리 생성>-------------------------------------------------------

dic_1 = {
    "name":"Kim",
    "age":13
}
dic_1
{'name': 'Kim', 'age': 13}

-------------------------------------------------------< 딕셔너리 사용>-------------------------------------------------------

1.값 추가

dic = {}    #추가
dic['tell'] = '010-2345'
{'tell': '010-2345'}

2.삭제 ( dell, pop )

dic_1 = {
    "name":"Kim",
    "age":13
}
del dic_1['name']

dic_1.pop()  #index 미지정->마지막 요소 return
{'age': 13}

3. 값 추출 (get,[ ]의 차이)

 

dic_1 = {
    "name":"Kim",
    "age":13
}
dic_1.get('name')	#없는 Key를 사용해도 에러 안남 (None 출력)
dic_1['name']		#없는 Key를 사용 시 에러 (KeyError 출력)
Kim
Kim

-------------------------------------------------------<모든 Key or Value 추출_for문 이용>-------------------------------------------------------

dic_1 = {
    "name":"Kim",
    "age":13
}

for i in dic_1:  #Key 추출
    print(i)
    
for i in dic_1:  #Value 추출
    print(dic_1[i])
name
age
Kim
13

-------------------------------------------------------< type()  is ~ 사용하기 >-------------------------------------------------------

type("문자열") is str      #문자열인지

type( [ ] ) is list      #리스트인지

type( { } ) is dict    #딕셔너리인지

character = {
    "name" : "기사",
    "level" : 12,
    "items" : {
        "sword" : "불꽃의 검",
        "armor" : "풀플레이트"
    },
    "skill" : ["베기", "세게 베기", "아주 세게 베기"]
}

for key in character:
    if type(character[key]) is dict:
        for key_1 in character[key]:
            print('{} : {}'.format(key_1,character[key][key_1]))
    elif type(character[key]) is list:
        for key_2 in character[key]:
            print('{} : {}'.format(key,key_2))
    else:
        print('{} : {}'.format(key,character[key]))
name : 기사
level : 12
sword : 불꽃의 검
armor : 풀플레이트
skill : 베기
skill : 세게 베기
skill : 아주 세게 베기

2021.04.18 - [심심하면. 잡다한 지식] - (30초) 곤약은 뭘로 만드는 걸까?? (구약감자)

반응형