클라우드 낚시꾼

[Python] 파이썬(Python) 딕셔너리(해시 테이블) 관련 함수, 메서드 모음 본문

Programming Language/Python 활용

[Python] 파이썬(Python) 딕셔너리(해시 테이블) 관련 함수, 메서드 모음

KanuBang 2024. 9. 12. 17:51
728x90
 
딕셔너리 생성 
 
# 딕셔너리 생성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