program/python

[python] 사전 dictionary

momoa210 2024. 1. 28. 15:17



Python의 딕셔너리는 키와 값으로 이루어진 자료형
생성 방법 2가지


첫 번째 방법은 중괄호 {}를 사용하는 것이고 
두 번째 방법은 내장 함수 dict()를 사용하는 것입니다.


#빈 딕셔너리 선언하기
my_dictionary = {}
print(my_dictionary)
#type() 함수를 통해 자료형을 확인하기
print(type(my_dictionary))
#출력된 결과
#{}
#<class 'dict'>



#빈 딕셔너리 선언하기
my_dictionary = dict()
print(my_dictionary)
#type() 함수를 통해 자료형을 확인하기
print(type(my_dictionary))
#출력된 결과
#{}
#<class 'dict'>


요소가 포함된 딕셔너리 선언하기

dictionary_name = {키: 값}

#딕셔너리 선언하기
my_information = {'name': 'Boyeon', 'age': 29, 'location': 'Seoul'}
print(my_information)
#자료형 확인하기
print(type(my_information))
#출력된 결과
#{'name': 'Boyeon', 'age': 29, 'location': 'Seoul'}
#<class 'dict'>



#dict() 함수를 사용해 딕셔너리 생성하기
my_information = dict({'name': 'Boyeon', 'age': 29, 'location': 'Seoul'})
print(my_information)
#자료형 확인하기
print(type(my_information))
#출력된 결과
#{'name': 'Boyeon', 'age': 29, 'location': 'Seoul'}
#<class 'dict'>



fromkeys() 메서드
딕셔너리_이름 = dict.fromkeys(sequence,value)


#일련의 문자열 생성하기
cities = ('Paris','Athens', 'Madrid')
#fromkeys() 메서드를 사용해 `my_dictionary`라는 딕셔너리 생성하기
my_dictionary = dict.fromkeys(cities)
print(my_dictionary)
#{'Paris': None, 'Athens': None, 'Madrid': None}


#일련의 문자열 생성하기
cities = ('Paris','Athens', 'Madrid')
#단일 값을 생성하기
continent = 'Europe'
my_dictionary = dict.fromkeys(cities,continent)
print(my_dictionary)
#출력된 결과
#{'Paris': 'Europe', 'Athens': 'Europe', 'Madrid': 'Europe'}


Python 딕셔너리 내의 키는 수정 불가능한(immutable) 타입

Python에서 수정 불가능한 데이터 타입은 정수(integers), 문자열(strings), 튜플(tuples), 실수형(floating point numbers), 그리고 불린 자료형(Booleans)입니다.

딕셔너리의 키는 집합 자료형(sets), 리스트(lists), 또는 딕셔너리(dictionaries)와 같은 수정 가능한(mutable) 데이터 타입일 수 없습니다.


my_dictionary = {True: "True",  1: 1,  1.1: 1.1, "one": 1, "languages": ["Python"]}
print(my_dictionary)
#출력된 결과
#{True: 1, 1.1: 1.1, 'one': 1, 'languages': ['Python']}


my_dictionary = {["Python"]: "languages"}
print(my_dictionary)
#출력된 결과
#line 1, in <module>
#    my_dictionary = {["Python"]: "languages"}
#TypeError: unhashable type: 'list'


#이렇게 딕셔너리에 `name` 키가 두 번 있을 수 없습니다
my_dictionary = {'name': 'Boyeon', 'name': 'Ihn'}
#하지만 딕셔너리에 `Seoul`이라는 값은 중복될 수 있습니다
my_information = {'birthplace': 'Seoul', 'current_location': 'Seoul'}


딕셔너리의 키-값(key-value) 개수 확인하기
my_information = {'name': 'Dionysia', 'age': 28, 'location': 'Athens'}
print(len(my_information))
#출력된 결과
#3


주어진 딕셔너리의 모든 키-값 보기

year_of_creation = {'Python': 1993, 'JavaScript': 1995, 'HTML': 1993}
print(year_of_creation.items())
#출력된 결과
#dict_items([('Python', 1993), ('JavaScript', 1995), ('HTML', 1993)])

 

 

for key, value in year_of_creation.items():

    #key, value 값 포함됨 


딕셔너리의 모든 키(key) 보기
year_of_creation = {'Python': 1993, 'JavaScript': 1995, 'HTML': 1993}
print(year_of_creation.keys())
#출력된 결과
#dict_keys(['Python', 'JavaScript', 'HTML'])

 

if check not in year_of_creation.keys():

    #check 에 해당하는 key가 없는 경우 키를 추가할 수 있음


딕셔너리의 모든 값(values) 보기
year_of_creation = {'Python': 1993, 'JavaScript': 1995, 'HTML': 1993}
print(year_of_creation.values())
#출력된 결과
#dict_values([1993, 1995, 1993])



딕셔너리의 특정 키-값에 접근하기
#기존 리스트
my_list = [1993, 1995, 2022]
#대괄호와 인덱스 번호를 사용해 첫 번째 요소 접근하기
first_element = my_list[0]
print(first_element)
#출력된 결과
# 1993

dictionary_name[key]

my_information = {'name': 'Dionysia', 'age': 28, 'location': 'Athens'}
#'age' 키에 할당된 값 접근하기
print(my_information['age'])
#출력된 결과
#28

my_information = {'name': 'Dionysia', 'age': 28, 'location': 'Athens'}
#존재하지 않는 'job' 키에 할당된 값 접근하기
print(my_information['job'])
#출력된 결과
#line 4, in <module>
#    print(my_information['job'])
#KeyError: 'job'


my_information = {'name': 'Dionysia', 'age': 28, 'location': 'Athens'}
#search for the 'job' key
print('job' in my_information)
#출력된 결과
#False



my_information = {'name': 'Dionysia', 'age': 28, 'location': 'Athens'}
#get() 메서드를 통해 'job' 키에 접근하기
print(my_information.get('job'))
#출력된 결과
#None

my_information = {'name': 'Boyeon', 'age': 29, 'location': 'Seoul'}
#get() 메서드를 통해 'job' 키에 접근하기
print(my_information.get('job', '이 값은 존재하지 않습니다'))
#출력된 결과
#이 값은 존재하지 않습니다



딕셔너리 수정하기

딕셔너리에 새 키-값 추가하기
dictionary_name[key] = value

my_dictionary = {}
#빈 딕셔너리에 키-값 추가하기
my_dictionary['name'] = "Boyeon Ihn"
#딕셔너리 출력하기
print(my_list)
#출력된 결과
#{'name': 'Boyeon Ihn'}



my_dictionary = {}
#빈 딕셔너리에 키-값 추가하기
my_dictionary['name'] = "Boyeon Ihn"
#키-값 또 추가하기
my_dictionary['age'] = 29
#딕셔너리 출력하기
print(my_dictionary)
#출력된 결과
#{'name': 'Boyeon Ihn', 'age': 29}

추가하려는 키가 해당 사전에 이미 있고 다른 값을 할당하는 경우, 기존에 있는 키의 값만 업데이트될 뿐, 새 키-값이 추가되지 않습니다.

my_dictionary = {'name': 'Boyeon Ihn', 'age': 29}
print(my_dictionary)
#'age' 키를 새로 생성하고 값을 할당하려고 시도해봅니다
#하지만 'age' 키는 이미 딕셔너리에 존재한 상황입니다.
my_dictionary['age'] = 46
#이런 경우, 존재하고 있는 'age'의 값이 29에서 46로 업데이트 될 뿐, 새 키-값이 추가되지 않습니다
print(my_dictionary)
#출력된 결과
#{'name': 'Boyeon Ihn', 'age': 29}
#{'name': 'Boyeon Ihn', 'age': 46}



my_dictionary = {'name': 'Boyeon Ihn', 'age': 29}
#'age' 키를 추가하려고 합니다. 추가하기 전에, 'age' 키가 이미 있는지 확인해봅시다.
print('age' in my_dictionary)
#출력된 결과
#True



딕셔너리의 기존 키-값 수정하기
dictionary_name[existing_key] = new_value
my_dictionary = {'name': 'Boyeon Ihn', 'age': 29}
my_dictionary['age'] = 46
print(my_dictionary)
#출력된 결과
#{'name': 'Boyeon Ihn', 'age': 29}



키 값 수정과 추가 동시에 하기 
my_dictionary = {'name': 'Boyeon Ihn', 'age': 29}
my_dictionary.update(name= 'Mike Green', age = 46, occupation = "software developer")
print(my_dictionary)
#출력된 결과
#{'name': 'Mike Green', 'age': 46, 'occupation': 'software developer'}



numbers = {'one': 1, 'two': 2, 'three': 3}
more_numbers = {'four': 4, 'five': 5, 'six': 6}
#'numbers' 딕셔너리 업데이트하기
#`more_numbers' 딕셔너리의 요소들을 기존 딕셔너리에 추가합니다
numbers.update(more_numbers)
print(numbers)
#출력된 결과
#{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}


딕셔너리의 키-값 삭제하기
del dictionary_name[key]

my_information = {'name': 'Boyeon', 'age': 29, 'location': 'Seoul'}
del my_information['location']
print(my_information)
#출력된 결과
#{'name': 'Boyeon', 'age': 29}

dictionary_name.pop(key)  
#삭제와 값 꺼내기를 같이 함


my_information = {'name': 'Boyeon', 'age': 29, 'location': 'Seoul'}
city = my_information.pop('location')
print(my_information)
print(city)
#출력된 결과
#{'name': 'Boyeon', 'age': 29}
#Seoul


my_information = {'name': 'Boyeon', 'age': 29, 'location': 'Seoul'}
my_information.pop('occupation')
print(my_information)
#출력된 결과
#line 3, in <module>
#   my_information.pop('occupation')
#KeyError: 'occupation'


my_information = {'name': 'Boyeon', 'age': 29, 'location': 'Seoul'}
my_information.pop('occupation','Not found') # 두번째 인자를 추가 하면 에러 발생은 안 함 
print(my_information)
#출력된 결과
#{'name': 'Boyeon', 'age': 29, 'location': 'Seoul'}



딕셔너리의 마지막 키-값만 삭제
dictionary_name.popitem()


my_information = {'name': 'Boyeon', 'age': 29, 'location': 'Seoul'}
popped_item = my_information.popitem()
print(my_information)
print(popped_item)
#출력된 결과
#{'name': 'Boyeon', 'age': 29}
#('location', 'Seoul')

딕셔너리에 포함된 모든 키-값을 삭제
my_information = {'name': 'Boyeon', 'age': 29, 'location': 'Seoul'}
my_information.clear()
print(my_information)
#출력된 결과
#{}







'program > python' 카테고리의 다른 글

[python] 리스트와 문자열  (0) 2024.01.28
[python] aliasing  (0) 2024.01.28
[python] for문 Range  (0) 2024.01.28
[Python]소수점,올림,반올림  (0) 2024.01.28
[python] list 정렬 sort sored  (1) 2024.01.28