안녕하세요, 코딩 푸는 남자 입니다.!
오늘은 Python 기초편에서 Dictionary 객체에 대해 소개해 볼까 합니다.
Dictionaries:
Dictionary는 Key - Value 형태로 데이터를 관리하는 객체 입니다.
예를 들어 다음과 같은 key와 Value가 있다고 가정해 보겠습니다.
이 경우, 다음과 같이 dictionary 객체를 생성 할수 있습니다.
dictionary_exam = {"name": "Alice", "age": 30, "is_student": False}
이제 사용자는 Key값을 통해, 연결되어 있는 Value에 접근 가능 합니다.
또한 이때 Key값은 중복이 불가능한, 유일한 값이어야 합니다.
그리고, Key를 통해 Value에 접근 가능 하지만, Value를 통해 Key에 접근은 불가능 합니다.
Creating Dictionaries:
Dictionarie를 생성하기 위해서는 {} 를 사용합니다.
한번 다음 예제를 통해 알아 보도록 하겠습니다.
Example:
# empty dictionary
empty_dic = {}
# A dictionary of integers
numbers = {"one": 1, "two": 2, "three": 3}
# A dictionary with mixed value types
mixed = {"name": "Alice", "age": 30, "is_student": False}
Accessing Dictionary Items:
생성한 Dictionary는 Key를 통해 Value에 접근 할 수 있습니다.
Example:
print(numbers["two"]) # Output: 2
print(mixed["name"]) # Output: Alice
Note: dictionarie의 key는 unique해야 하며, 대/소문자를 구분 합니다.
Modifying Dictionaries:
Dictionarie 생성된 이후, 신규 Key-Value를 추가, 기존 Value의 변경, 기존 Key-Value의 제거가 가능 합니다.
단, 기존 Key값에 대한 변경은 불가능 합니다.
- Adding New Key-Value Pairs: 다음 방법을 통해 신규 Key - Value 추가가 가능 합니다.
Example:
# mixed = {"name": "Alice", "age": 30, "is_student": False} mixed["hobby"] = "Reading" print(mixed) # Output: {'name': 'Alice', 'age': 30, 'is_student': False, 'hobby': 'Reading'}
- Modifying Existing Values: 특정 Key에 해당하는 Value는 변경 가능 합니다. 다음은 age의 value가 30에서 31로 변경되는 예제 입니다.
Example:
# mixed: {'name': 'Alice', 'age': 30, 'is_student': False, 'hobby': 'Reading'} mixed["age"] = 31 print(mixed) # Output: {'name': 'Alice', 'age': 31, 'is_student': False, 'hobby': 'Reading'}
- Removing Key-Value Pairs: Key-Value의 제거는 pop(), del 구문 두가지 방법으로 가능 합니다.
Example with pop():
# mixed: {'name': 'Alice', 'age': 31, 'is_student': False, 'hobby': 'Reading'} removed_value = mixed.pop("is_student") print(mixed) # Output: {'name': 'Alice', 'age': 31, 'hobby': 'Reading'} print("Removed Value:", removed_value) # Output: False
Example with del:
# mixed: {'name': 'Alice', 'age': 31, 'hobby': 'Reading'} del mixed["hobby"] print(mixed) # Output: {'name': 'Alice', 'age': 31}
Dictionary Methods:
Dictionary에서 자주 사용하는 methods는 다음과 같습니다.
- keys(): Returns a list of all the keys in the dictionary.
person = {'name': 'Alice', 'city': 'New York'} print(person.keys()) # Output: dict_keys(['name', 'city'])
- values(): Returns a list of all the values in the dictionary.
person = {'name': 'Alice', 'city': 'New York'} print(person.values()) # Output: dict_values(['Alice', 'New York'])
Conclusion:
오늘은 Python에서 제공하는 Dictionary에 대해 간단히 알아 보았습니다.
감사합니다.