728x90
728x90
dictionary(사전)

특정 키에 맞는 value를 가지는 것들이 딕셔너리의 요소들

 

기본형

sd={
    "name":"윤",
    "직업":"편집자",
    "나이":20
}
print(sd)
print(type(sd))

#{'name': '윤', '직업': '편집자', '나이': 20}
#<class 'dict'>

 

person={
    "이름":"김",
    "나이":10,
    "집":False,
    "취미":{"잠","음악감상"}
}
print(person) #{'이름': '김', '나이': 10, '집': False, '취미': {'음악감상', '잠'}}
print(person["나이"])  #10
print(person[0])  #error

 

 

키, 값 출력

person={
    "이름":"김",
    "나이":10,
    "집":False,
    "취미":{"잠","음악감상"}
}

print(person.keys())
print(person.values())
#dict_keys(['이름', '나이', '집', '취미'])
#dict_values(['김', 10, False, {'잠', '음악감상'}])

 

 

추가

person={
    "이름":"김",
    "나이":10,
    "집":False,
    "취미":{"잠","음악감상"}
}

person["신장"]=170
person["주소"]="서울시"

print(person) 
#{'이름': '김', '나이': 10, '집': False, '취미': {'잠', '음악감상'}, '신장': 170, '주소': '서울시'}

 

 

항목을 튜플로 변환

person={
    "이름":"김",
    "나이":10,
    "집":False,
    "취미":{"잠","음악감상"}
}

print(person.items()) 
#dict_items([('이름', '김'), ('나이', 10), ('집', False), ('취미', {'음악감상', '잠'})])

 

 

중첩 딕셔너리

person={
    "김" : {"결혼":False, "나이":29},
    "박" : {"결혼":True, "나이":25}
}

print(person)  #{'김': {'결혼': False, '나이': 29}, '박': {'결혼': True, '나이': 25}}
person1={
        "이름":"김박",
        "나이":29
}
person2={
        "이름":"김민",
        "나이":28
}

person={
    "첫째" : person1,
    "둘째" : person2
}

print(person) #{'첫째': {'이름': '김박', '나이': 29}, '둘째': {'이름': '김민', '나이': 28}}

 

728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,

v