250x250
Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | 26 | 27 | 28 |
| 29 | 30 | 31 |
Tags
- getreference
- aws saa-c03
- 플랫폼 클래스 로더
- 스프링 컨테이너
- python list method
- 어플리케이션 클래스 로더
- 알고리즘
- 파이썬 리스트 메서드
- 파이썬
- 자료구조
- java
- 심볼릭 레퍼런스
- 컴포넌트 스캔
- 스프링
- BFS
- Spring
- 딕셔너리
- 클래스 로더 계층
- 다이렉트 레퍼런스
- 백준
- python
- 파이썬 문자열 메서드
- 코딩테스트
- 객체지향
- 2026 AWS SAA-C03
- dfs
- AWS SAA-C03 합격후기
- 자바
- stop the world
- 부트스트랩 클래스 로더
Archives
- Today
- Total
클라우드 낚시꾼
[Python] 파이썬(Python) 딕셔너리(해시 테이블) 관련 함수, 메서드 모음 본문
Programming Language/Python 활용
[Python] 파이썬(Python) 딕셔너리(해시 테이블) 관련 함수, 메서드 모음
KanuBang 2024. 9. 12. 17:51728x90
딕셔너리 생성
# 딕셔너리 생성1: {} 사용
tom = {
"name": "tom",
"age": 25,
"city": "London"
}
# 딕셔너리 생성2: dict() 생성자 이용
smith = dict(name="smith", age=24, city="Manchester")
- 생성 방법1: {"key1": value1, "key2":value2}
- 생성 방법2: dict(key1=value1, key2=value2)
zip()을 이용한 딕셔너리 생성
dic = dict(zip(["w","s","d","a"], [1,-1,10,-10]))
# {'w': 1, 's': -1, 'd': 10, 'a': -10}
zip() 함수는 각각의 iterable에서 같은 위치에 있는 요소들을 하나씩 묶어 주는 역할을 한다. 생성된 ZipObject를 dict() 생성자에 넣으면 딕셔너리를 생성할 수 있다.
딕셔너리 접근
# 딕셔너리 접근1: []을 이용한 접근, key가 없다면 keyError 발생
print(tom["name"])
# 딕셔너리 접근2: get을 이용한 접근
print(smith.get("age"))
print(smith.get("asdf",70))
- 접근 방법1: dictionary[key]
- 접근 방법2: dictionaty.get(key)
dictionaty.get(key) 방식은 key가 딕셔너리에 없어도 KeyError 발생시키지 않고 none을 리턴한다.
단, 두 번째 파라미터가 있다면 그 값을 리턴한다.
딕셔너리 업데이트, 추가, 삭제
# 딕셔너리 업데이트 및 추가
smith['age']=99 # 존재하는 key로 value 업데이트
smith['height'] = 170 # key-value 쌍 추가
# 딕셔너리 key-value 쌍 삭제
del smith["city"]
print(tom.pop("city"))
- 딕셔너리 업데이트 및 추가: dictionary[key] = updatedValue, dictionary[newKey] = newValue
- 딕셔너리 key-value 삭제
- del dictionary["key"]
- dictionary.pop("key"): key-value pair을 삭제하면서 해당 value 값 반환
유용한 딕셔너리 메서드
person = {
'name': 'Alice',
'age': 30,
'city': 'New York'
}
keys_view = person.keys()
print("Keys:", keys_view) # 결과: dict_keys(['name', 'age', 'city'])
values_view = person.values()
print("Values:", values_view) # 결과: dict_values(['Alice', 30, 'New York'])
items_view = person.items()
print("Items:", items_view) # 결과: dict_items([('name', 'Alice'), ('age', 30), ('city', 'New York')])
additional_info = {
'email': 'alice@example.com',
'age': 31
}
person.update(additional_info)
print("Updated Dictionary:", person)
# 결과: {'name': 'Alice', 'age': 31, 'city': 'New York', 'email': 'alice@example.com'}
- keys(): 딕셔너리의 모든 key를 포함하는 view object를 반환
- values(): 딕셔너리의 모든 value를 포함하는 view object를 반환
- tems(): 딕셔너리의 모든 key-value를 포함하는 view object를 반환
- update(): 현재 딕셔너리와 다른 딕셔너리를 병합
딕셔너리 comprehension
tmp =[1,2,3,4,5]
square_dict = {x: x**2 for x in tmp}
print(square_dict)
리스트 comprehension과 유사하게, 딕셔너리 comprehension를 이용하여 딕셔너리를 생성할 수 있다.
딕셔너리 Iteration
# 딕셔너리에 key 존재하는 지 확인하기
if "age" in smith:
print("key age exists in smith dictionary")
# 딕셔너리에서 Iteration 하기
for key in smith:
print(key)
for value in smith.values():
print(value)
for key,value in smith.items():
print(key,value)
728x90
'Programming Language > Python 활용' 카테고리의 다른 글
| [Python] 파이썬(Python) 유용한 리스트(list) 메서드 모음 (1) | 2024.09.16 |
|---|---|
| [Python] 파이썬(Python) 유용한 문자열(String) 메서드 모음 (0) | 2024.09.14 |
| [Python3] 딕셔너리 정렬하기 with lambda (0) | 2024.03.20 |
| [Python3] Python 출력문 정리 (0) | 2024.03.15 |
| [Python3] Python 대소문자 관리 (upper, lower) (0) | 2024.03.15 |