딕셔너리

임승환·2024년 4월 4일

Python

목록 보기
10/20

딕셔너리

>> {}안에 키 : 값의 형식을 가진 유일한 데이터를 콤마( , )로 구분해 하나 이상 저장할 수 있는 컬렉션 자료형

  • 인덱스를 제공하지 않음
  • 순서의 개념이 없음
  • 중복을 허용하지 않음
  • key값으로 리스트 불가능

딕셔너리 내포를 이용한 다중조건 정렬

N, M = map(int, input().split())
d = {}
for i in range(N):
    s = input()
    if len(s) < M:
        continue
    if s in d:
        d[s] += 1
    else:
        d[s] = 1
d2 = sorted(d.items(), key=lambda x: (-x[-1], -len(x[0]), x[0]))
# sorted에서 람다함수를 통해서 다중 조건을 걸 수 있다.
for i in d2:
    print(i[0])
# 1. 자주 나오는 단어일 수록 앞에 배치한다. -x[-1]
# 2. 단어 길이가 길수록 앞에 배치 -len(x[0])
# 3. 알파벳 사전 순으로 앞에 있는 단어일 수록 앞에 배치 x[0]

딕셔너리 생성

data_dict1={
	"홍길동": 20,
	"이순신": 45,
	"강감찬": 35
}
print(data_dict1)
# {'홍길동': 20, '이순신': 45, '강감찬': 35}
data_dict2 = dict(홍길동=20, 이순신=45, 강감찬=35)
# 이렇게 쓸 떄 홍길동에 ''안 씀
print(data_dict2)
# {'홍길동': 20, '이순신': 45, '강감찬': 35}
  • 매개변수 목록을 기술해 딕셔너리 생성
  • 이렇게 쓸 떄 홍길동에 ''안 씀
data_tuple1 = (('홍길동', 20), ('이순신', 45), ('강감찬', 35))
data_dict3 = dict(data_tuple1)
print(data_dict3)
# 튜플 객체를 dict함수의 인자로 전달해 data_dict3 딕셔너리 객체 생성
# {'홍길동': 20, '이순신': 45, '강감찬': 35}
  • 튜플 객체를 dict함수의 인자로 전달해 딕셔너리 객체 생성
data_list1 = [('홍길동', 20),('이순신', 45), ('강감찬', 35)]
data_dict4 = dict(data_list1)
print(data_dict4)
# {'홍길동': 20, '이순신': 45, '강감찬': 35}
  • 리스트를 dict함수인자로 전달해 딕셔너리 생성
data_set1 = {('홍길동', 20), ('이순신', 45), ('강감찬', 35)}
data_dict5 = dict(data_set1)
print(data_dict5)
# {'홍길동': 20, '이순신': 45, '강감찬': 35}
  • set 객체를 dict함수로 딕셔너리 생성
data_dict1={
	"홍길동": 20,
	"이순신": 45,
	"강감찬": 35
}
print(f"data_dict1['홍길동'] => {data_dict1['홍길동']}")
# data_dict1['홍길동'] => 20
  • 딕셔너리 읽기.

딕셔너리 항목 추가

data_dict1={
	"홍길동": 20,
	"이순신": 45,
	"강감찬": 35
}
data_dict1['을지문덕'] = 40
print(data_dict1)

# {'홍길동': 20, '이순신': 45, '강감찬': 35, '을지문덕': 40}
18:33

dict.update({})

data_dict1.update({'신사임당': 50, '유관순':16})
print(data_dict1)

# {'홍길동': 20, '이순신': 45, '강감찬': 35, '을지문덕': 40, '신사임당': 50, '유관순': 16}

딕셔너리 항목 변경

data_dict1={
	"홍길동": 20,
	"이순신": 45,
	"강감찬": 35
}
data_dict1['강감찬'] = 40 # 객체이름[중복되는 키] = 값
print(data_dict1)

# {'홍길동': 20, '이순신': 45, '강감찬': 40}

dict.update({})

data_dict1={
	"홍길동": 20,
	"이순신": 45,
	"강감찬": 35
}
data_dict1.update({"홍길동":25, "이순신": 48})
# 키가 동일할 때 기존 항목 변경
print(data_dict1)

# {'홍길동': 25, '이순신': 48, '강감찬': 35}

딕셔너리 항목 제거

data_dict1={
	"홍길동": 20,
	"이순신": 45,
	"강감찬": 35,
    "을지문덕": 40
}
del data_dict1["강감찬"]
print(data_dict1)
data_dict1.pop('이순신')
print(data_dict1)

# {'홍길동': 20, '강감찬': 35, '을지문덕': 40}
data_dict1.clear() # 모든 항목이 삭제되며, {} 빈 딕셔너리 객체 리터럴을 출력

딕셔너리 항목 확인

print('홍길동' in data_dict1) # True
print('홍길동' not in data_dict1) # True

딕셔너리와 for문

# for key in data_dict1.keys(): 아래와 같은 식이다.
for key in data_dict1:
    print(f'{key}, {data_dict1[key]}') # 키값, 벨류값

for item in data_dict1.items():
    print(f'{item[0]}, {item[1]}') # 키값, 벨류값

for key, value in data_dict1.items():
    print(f'{key}, {value}')

# 홍길동, 20
# 이순신, 45
# 강감찬, 35
for value in data_dict1.values():
    print(f'{value}')

# 20
# 45
# 35

for key in data_dict1.keys():
    print(f'{key}')

# 홍길동
# 이순신
# 강감찬

딕셔너리 내포

data_set1 = {item for item in data_dict1.items()}
# {('홍길동', 20), ('이순신', 45), ('강감찬', 35)}
# set형태로 출력된다.
data_dict2 = {key: data_dict1[key] for key in data_dict1}
# 딕셔너리 내포 기능으로 data_dict1의 항목을 가진 data_dict2 딕셔너리 객체 생성

data_dict3 = {key: data_dict1[key] for key in data_dict1.keys()}

data_dict4 = {item[0]: item[1] for item in data_dict1.itmes()}

data_dict5 = {key: value for key, value in data_dict1.items()}

# 위의 dict2~5는 전부 딕셔너리 형태의 아래와 같은 값을 반환한다.
# {'홍길동': 20, '이순신': 45, '강감찬': 35}
29.49

딕셔너리 정렬 키 기준

data={
	"홍길동": 20,
	"이순신": 45,
	"강감찬": 35,
  "을지문덕": 40
}
d1 = sorted(data.items())
print(d1)
# 결과값
[('강감찬', 35), ('을지문덕', 40), ('이순신', 45), ('홍길동', 20)]

딕셔너리 정렬 벨류 기준

data={
	"홍길동": 20,
	"이순신": 45,
	"강감찬": 35,
  "을지문덕": 40
}
d2 = sorted(d.items(), key = lambda x: x[1])
print(d2)
# 결과값
[('홍길동', 20), ('강감찬', 35), ('을지문덕', 40), ('이순신', 45)]
profile
주니어 개발자

0개의 댓글