Python을 하다 보면, 한줄씩 실행 하면서 결과를 확인하면서 코딩을 해야 하는 경우가 있습니다.

이러한 방식을 대화형 방식이라고 하며, 영어로 Interactive Mode라고 합니다.

보통 이런 경우 Jupyter Notebook을 이용하는데, VS Code에서도 간단히 Jupyter Notebook 확장팩을 설치하여,

Interactive Mode 이용이 가능 합니다.

 

우선 다음과 같이 예제 코드를 작성해 보겠습니다.

import pandas as pd
from openpyxl import Workbook

#price라는 Series 생성
price = pd.Series([500, 1000, 2000, 4000])
print("Series type:")
print(type(price)) #Series는 pandas의 클래스

 

그 다음, Jupyter Extension을 설치 합니다.

 

 

다시 코드로 돌아와서, # %% 를 표시하면, 아래와 같이 # %%마다 분리된 Cell로 인식 하게 됩니다.

그림에서 표시된 Run Above를 클릭하면, 해당 Cell 위에 있는 Python Code들이 모두 실행 되면서,

다음과 같이 화면 우측에는 Interactive window, 화면 하단에는 JUPYTER 정보 가 표시 됩니다.

Interactive Mode이기 때문에, 프로그램은 종료 되지 않고, 11번 라인에서 대기 하게 됩니다.

 

다음과 같이 11번 라인에 추가적인 코드를 작성한 뒤, Run Cell을 클릭하면 아래와 같이 다음 코드가 실행 되면서 결과가 이어서 업데이트 됩니다.

 

 

예제로 사용된 전체 코드는 다음과 같습니다.

import pandas as pd
from openpyxl import Workbook

# %%
#price라는 Series 생성
price = pd.Series([500, 1000, 2000, 4000])
print("Series type:")
print(type(price)) #Series는 pandas의 클래스


# %%
print("Series 전체 출력")
print(price)


# %%
print("Series 인덱싱")
print(price[0])
print(price[1])

price.to_excel('test.xlsx')


# 엑셀파일 쓰기
write_wb = Workbook()

# 이름이 있는 시트를 생성
write_ws = write_wb.create_sheet('생성시트')

# Sheet1에다 입력
write_ws = write_wb.active
write_ws['A1'] = '숫자'

#행 단위로 추가
write_ws.append([1,2,3])

#셀 단위로 추가
write_ws.cell(5, 5, '5행5열')
write_wb.save("test2.xlsx")
# %%

'Python 기초 > 1. 환경설정' 카테고리의 다른 글

Visual Studio Code를 이용한 Python 실행  (0) 2024.07.21
특정 버전 Python 실행하기  (0) 2024.05.11

저는 요즘 대부분의 코딩을 Visual Studio Code (VSCode)로 하고 있습니다.

이번에는 VSCode를 사용하여 Python 환경을 설정하고, Python 코드를 실행하는 기본적인 방법을 알아보겠습니다.

 

1. VSCode 설치

먼저, Visual Studio Code를 설치해야 합니다. VSCode는 Windows, macOS, Linux에서 사용할 수 있습니다.

  1. VSCode 공식 사이트로 이동합니다.
  2. 운영체제에 맞는 설치 파일을 다운로드하고 설치합니다.
  3. 설치 시 "Add Python to PATH" 옵션을 체크하여 환경 변수를 설정합니다.
    만약 해당 옵션을 체크 하지 못했다면, 환경 변수 Path에 아래 두가지를 본인의 환경에 맞게 설정해 주시면 됩니다. 


  4. 설치가 완료되면 터미널(또는 명령 프롬프트)을 열고 python --version 명령어를 입력하여 설치가 제대로 되었는지 확인합니다.


2. VSCode에서 Python 확장 설치

VSCode에서 Python 개발을 위해 Microsoft에서 제공하는 Python 확장을 설치해야 합니다.

  1. VSCode를 엽니다.
  2. 왼쪽 사이드바에서 Extensions 뷰(네모 아이콘)를 클릭하거나 Ctrl+Shift+X 단축키를 누릅니다.
  3. 검색창에 "Python"을 입력하고 Python (Microsoft) 확장을 설치합니다.

 

3. Python 인터프리터 설정

Python 확장을 설치한 후, 프로젝트에서 사용할 Python 인터프리터를 설정해야 합니다.

  1. Command Palette 열기: Ctrl+Shift+P
  2. Python: Select Interpreter 입력 및 선택
  3. 사용 가능한 Python 인터프리터 목록이 나타나면 원하는 인터프리터를 선택합니다.

 

4. Python 파일 생성 및 실행

이제 Python 파일을 생성하고 실행할 준비가 되었습니다.

  1. VSCode에서 새로운 파일을 생성합니다: Ctrl+N
  2. 파일을 저장합니다: Ctrl+S (파일 확장자는 .py로 설정, 예: main.py)
  3. main.py 파일에 다음 코드를 입력합니다.
    print("Hello, World!")


  4. Python을 실행하기 위해 Terminal을 열기.



  5. python 실행
    py main.py


 

 

 

 

 

 

1. 멤버 접근 제한

Python에서는 클래스 멤버(변수와 메서드)의 접근 제한을 설정할 수 있습니다. C++이나 Java와 같은 언어에서는 public, protected, private 키워드를 사용하여 접근 제한을 명시하지만, Python에서는 이러한 키워드 대신 명명 규칙을 사용합니다.

1.1. Public 멤버

Public 멤버는 어디서든 접근 가능합니다. 변수나 메서드 이름 앞에 아무런 접두사를 붙이지 않습니다.

class MyClass:
    def __init__(self):
        self.public_variable = "I am public"

    def public_method(self):
        print("This is a public method")

# 인스턴스 생성
obj = MyClass()
print(obj.public_variable)  # 출력: I am public
obj.public_method()  # 출력: This is a public method

 

1.2. Protected 멤버

Protected 멤버는 서브 클래스에서 접근 가능합니다. 변수나 메서드 이름 앞에 한 개의 밑줄(_)을 붙입니다. 이는 암묵적으로 "이 멤버는 보호된 상태"임을 나타냅니다.

class MyClass:
    def __init__(self):
        self._protected_variable = "I am protected"

    def _protected_method(self):
        print("This is a protected method")

class SubClass(MyClass):
    def access_protected(self):
        print(self._protected_variable)  # 출력: I am protected
        self._protected_method()  # 출력: This is a protected method

# 인스턴스 생성
obj = SubClass()
obj.access_protected()

 

1.3. Private 멤버

Private 멤버는 클래스 내부에서만 접근 가능합니다. 변수나 메서드 이름 앞에 두 개의 밑줄(__)을 붙입니다. 이는 이름 맹글링(name mangling)을 통해 클래스 외부에서 접근할 수 없게 합니다.

class MyClass:
    def __init__(self):
        self.__private_variable = "I am private"

    def __private_method(self):
        print("This is a private method")

    def access_private(self):
        print(self.__private_variable)
        self.__private_method()

# 인스턴스 생성
obj = MyClass()
obj.access_private()  # 출력: I am private, This is a private method

# Private 멤버에 직접 접근 시도 (실패)
print(obj.__private_variable)  # AttributeError 발생
obj.__private_method()  # AttributeError 발생

 

2. 함수 재정의 (Method Overriding) 및 상속

Python에서는 클래스 상속을 통해 기존 클래스의 기능을 확장할 수 있습니다. 함수 재정의는 서브 클래스에서 부모 클래스의 메서드를 다시 정의하는 것을 의미합니다.

2.1. 기본 클래스와 서브 클래스

기본 클래스(부모 클래스)는 서브 클래스(자식 클래스)에 의해 상속됩니다. 서브 클래스는 부모 클래스의 모든 속성과 메서드를 상속받으며, 이를 추가하거나 재정의할 수 있습니다.

class Animal:
    def make_sound(self):
        print("Some generic sound")

class Dog(Animal):
    def make_sound(self):
        print("Bark")

class Cat(Animal):
    def make_sound(self):
        print("Meow")

# 인스턴스 생성
animal = Animal()
dog = Dog()
cat = Cat()

animal.make_sound()  # 출력: Some generic sound
dog.make_sound()  # 출력: Bark
cat.make_sound()  # 출력: Meow

 

2.2. 부모 메서드 호출

서브 클래스에서 부모 클래스의 메서드를 호출하려면 super()를 사용합니다.

class Animal:
    def make_sound(self):
        print("Some generic sound")

class Dog(Animal):
    def make_sound(self):
        super().make_sound()  # 부모 클래스의 메서드 호출
        print("Bark")

# 인스턴스 생성
dog = Dog()
dog.make_sound()
# 출력:
# Some generic sound
# Bark

 

2.3. 추상 클래스

Python에서는 abc 모듈을 사용하여 추상 클래스를 정의할 수 있습니다. 추상 클래스는 서브 클래스에서 반드시 구현해야 하는 메서드를 정의할 수 있습니다.

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def make_sound(self):
        pass

class Dog(Animal):
    def make_sound(self):
        print("Bark")

# 인스턴스 생성
dog = Dog()
dog.make_sound()  # 출력: Bark

# 추상 클래스는 인스턴스화할 수 없음
animal = Animal()  # TypeError 발생

 

3. 요약

  • 멤버 접근 제한: Public, Protected, Private 멤버를 명명 규칙을 통해 설정할 수 있습니다.
    • Public: 아무런 접두사 없이 정의, 어디서든 접근 가능.
    • Protected: 한 개의 밑줄(_)을 접두사로 사용, 서브 클래스에서 접근 가능.
    • Private: 두 개의 밑줄(__)을 접두사로 사용, 클래스 내부에서만 접근 가능.
  • 함수 재정의 및 상속: 서브 클래스에서 부모 클래스의 메서드를 재정의할 수 있으며, super()를 사용하여 부모 메서드를 호출할 수 있습니다.
  • 추상 클래스: abc 모듈을 사용하여 추상 클래스를 정의하고, 서브 클래스에서 반드시 구현해야 하는 메서드를 지정할 수 있습니다.

'Python 기초 > 6. Class' 카테고리의 다른 글

2. Class Method 종류와 용도  (0) 2024.07.07
1. Class 기초  (0) 2024.07.06

Python에서 객체 지향 프로그래밍(OOP)을 활용할 때, 클래스 메서드, 정적 메서드, 일반 메서드의 개념을 이해하는 것이 중요합니다. 이 세 가지 메서드는 각각의 목적과 사용 방식이 다르며, 각기 다른 상황에서 유용하게 사용할 수 있습니다. 이번 포스트에서는 이 메서드들의 차이점과 용도에 대해 자세히 알아보겠습니다.

 

1. 클래스 메서드, 정적 메서드, 일반 메서드 예제

다음은 세 가지 유형의 메서드와 변수를 포함하는 Calculator 클래스를 정의한 예제입니다. 이 클래스는 덧셈 연산을 수행하며, 클래스 변수, 인스턴스 변수, 일반 메서드, 클래스 메서드, 정적 메서드를 모두 포함합니다.

class Calculator:
    class_add_result = 0  # 클래스 변수

    def __init__(self):
        self.instance_add_result = 0  # 인스턴스 변수

    def add(self, value):  # 일반 메서드
        self.instance_add_result += value
        print(f"Instance add result: {self.instance_add_result}")

    @classmethod
    def class_add(cls, value):  # 클래스 메서드
        cls.class_add_result += value
        print(f"Class add result: {cls.class_add_result}")

    @staticmethod
    def static_add(x, y):  # 정적 메서드
        return x + y

# 인스턴스 생성
calc1 = Calculator()
calc2 = Calculator()

# 일반 메서드 호출
calc1.add(10)  # 출력: Instance add result: 10
calc2.add(20)  # 출력: Instance add result: 20

# 클래스 메서드 호출
Calculator.class_add(15)  # 출력: Class add result: 15
Calculator.class_add(25)  # 출력: Class add result: 40

# 정적 메서드 호출
result = Calculator.static_add(3, 7)
print(f"Static add result: {result}")  # 출력: Static add result: 10

 

2. 일반 메서드 (Instance Method)

일반 메서드는 클래스의 인스턴스에서 호출되는 메서드입니다. 이 메서드는 인스턴스 변수에 접근하고, 인스턴스의 상태를 변경하거나 사용하는 데 주로 사용됩니다. 일반 메서드는 self를 첫 번째 인자로 받습니다. self는 메서드가 호출된 인스턴스 객체를 참조합니다.

class Calculator:
    class_add_result = 0  # 클래스 변수

    def __init__(self):
        self.instance_add_result = 0  # 인스턴스 변수

    def add(self, value):  # 일반 메서드
        self.instance_add_result += value
        print(f"Instance add result: {self.instance_add_result}")

# 인스턴스 생성 및 메서드 호출
calc1 = Calculator()
calc2 = Calculator()
calc1.add(10)  # 출력: Instance add result: 10
calc2.add(20)  # 출력: Instance add result: 20

위 예제에서 add 메서드는 Calculator 클래스의 인스턴스 메서드입니다. 이 메서드는 인스턴스 변수 instance_add_result에 접근하여 사용됩니다.

 

3. 클래스 메서드 (Class Method)

클래스 메서드는 클래스 자체를 첫 번째 인자로 받는 메서드입니다. 이를 위해 @classmethod 데코레이터를 사용합니다. 클래스 메서드는 클래스 변수를 조작하거나 클래스 레벨의 동작을 정의하는 데 사용됩니다. 클래스 메서드는 cls를 첫 번째 인자로 받으며, 이는 호출된 클래스 객체를 참조합니다.

class Calculator:
    class_add_result = 0  # 클래스 변수

    def __init__(self):
        self.instance_add_result = 0  # 인스턴스 변수

    @classmethod
    def class_add(cls, value):  # 클래스 메서드
        cls.class_add_result += value
        print(f"Class add result: {cls.class_add_result}")

# 클래스 메서드 호출
Calculator.class_add(15)  # 출력: Class add result: 15
Calculator.class_add(25)  # 출력: Class add result: 40

위 예제에서 class_add 메서드는 클래스 메서드로, 클래스 변수 class_add_result에 접근하여 이를 변경합니다.

 

4. 정적 메서드 (Static Method)

정적 메서드는 클래스나 인스턴스와는 무관하게 동작하는 메서드입니다. @staticmethod 데코레이터를 사용하여 정의됩니다. 정적 메서드는 클래스나 인스턴스의 상태와 상관없는 독립적인 기능을 수행할 때 유용합니다.

class Calculator:
    @staticmethod
    def static_add(x, y):  # 정적 메서드
        return x + y

# 정적 메서드 호출
result = Calculator.static_add(3, 7)
print(f"Static add result: {result}")  # 출력: Static add result: 10

위 예제에서 static_add 메서드는 정적 메서드로, 두 숫자의 합을 계산하는 독립적인 기능을 수행합니다. 이 메서드는 클래스나 인스턴스의 상태와 무관하게 작동합니다.

 

정리

  • 일반 메서드: 인스턴스에서 호출되며, 인스턴스 변수에 접근하고 이를 조작하는 메서드입니다. 첫 번째 인자로 self를 받습니다.
  • 클래스 메서드: 클래스에서 호출되며, 클래스 변수를 조작하거나 클래스 레벨의 동작을 정의하는 메서드입니다. 첫 번째 인자로 cls를 받습니다. @classmethod 데코레이터를 사용합니다.
  • 정적 메서드: 클래스나 인스턴스와는 무관하게 동작하는 독립적인 메서드입니다. 첫 번째 인자로 self나 cls를 받지 않습니다. @staticmethod 데코레이터를 사용합니다.

 

'Python 기초 > 6. Class' 카테고리의 다른 글

3. member 및 method 관리  (0) 2024.07.07
1. Class 기초  (0) 2024.07.06

1. 클래스 생성

클래스를 생성하려면 class 키워드를 사용합니다. 클래스 내부에는 인스턴스 변수를 초기화하는 __init__ 메서드와 클래스 메서드 등을 정의할 수 있습니다.

class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species

    def make_sound(self):
        print("Some generic sound")

# 인스턴스 생성
animal = Animal("Generic Animal", "Unknown")
print(animal.name)  # 출력: Generic Animal
print(animal.species)  # 출력: Unknown
animal.make_sound()  # 출력: Some generic sound

 

2. 클래스 상속

클래스 상속은 기존 클래스를 확장하여 새로운 클래스를 만드는 방법입니다. 상속받는 클래스는 부모 클래스(또는 슈퍼 클래스)의 속성과 메서드를 모두 상속받으며, 이를 추가하거나 변경할 수 있습니다.

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name, "Dog")
        self.breed = breed

    def make_sound(self):
        print("Bark")

# 인스턴스 생성
dog = Dog("Buddy", "Golden Retriever")
print(dog.name)  # 출력: Buddy
print(dog.species)  # 출력: Dog
print(dog.breed)  # 출력: Golden Retriever
dog.make_sound()  # 출력: Bark

 

3. 메서드 정의

클래스 내부에서 정의된 함수는 메서드라고 불립니다. 메서드는 첫 번째 인자로 항상 self를 받는데, 이는 메서드가 호출되는 인스턴스를 가리킵니다.

class Cat(Animal):
    def __init__(self, name, color):
        super().__init__(name, "Cat")
        self.color = color

    def make_sound(self):
        print("Meow")

    def describe(self):
        print(f"{self.name} is a {self.color} cat.")

# 인스턴스 생성
cat = Cat("Whiskers", "black")
print(cat.name)  # 출력: Whiskers
print(cat.species)  # 출력: Cat
print(cat.color)  # 출력: black
cat.make_sound()  # 출력: Meow
cat.describe()  # 출력: Whiskers is a black cat.

 

'Python 기초 > 6. Class' 카테고리의 다른 글

3. member 및 method 관리  (0) 2024.07.07
2. Class Method 종류와 용도  (0) 2024.07.07

Python을 사용하다 보면, 여러 버전의 Python을 설치해야 하는 경우가 종종 생기게 됩니다.

이 경우, 특정 버전의 Python으로 실행 하고자 하면 다음과 같이 하면 됩니다.

py -3.6 main.py

 

마찬가지로, 3.6 버전으로 pip install하고자 하는 경우에는 다음과 같이 하면 됩니다.

py -3.6 -m pip install package_name

 

 

Python Sets

Introduction to Python Sets

안녕하세요, 코딩 푸는 남자 입니다.

오늘은 Python의 기본 객체중 Set 객체를 알아 보도록 하겠습니다.

Set 객체는 한국말로 하면 집합의 개념 입니다.

List처럼 순서가 있거나, Dictionary처럼 Key로 색인을 하는 경우가 아닌 경우 사용 가능 합니다.

우선 Set 객체에 대해 간단히 알아 보겠습니다.

 

Creating a Set

Set는 다음과 같이 두가지 방법을 이용해서 생성 가능 합니다.

# Using curly braces
fruits = {"apple", "banana", "cherry"}

# Using the set() function
colors = set(["red", "green", "blue"])

 

Note: Set에서 사용하는 element들은 중복이 불가능 합니다. 만약 중복 element를 생성하면, Set가 자동으로 중복을 제거 합니다. 이에 대해서는 후에 자세히 알아 보도록 하겠습니다.

 

Basic Set Operations

Adding Elements

add() method를 통해 신규 element를 추가 할 수 있습니다.

fruits.add("orange")

 

Removing Elements

제거하기 위해서는 remove() 혹은 discard() method 두가지가 이용 가능하며, 차이점은 아래와 같습니다.

fruits.remove("banana")  # Raises an error if 'banana' is not present
fruits.discard("banana")  # Does not raise an error if 'banana' is not present

 

Set Operations

Set 객체는 교집합 (&), 합집합 (|) , 차집합 (-) 과 같은 operation이 지원 됩니다.

a = {1, 2, 3}
b = {3, 4, 5}

# Union
print(a | b)  # Output: {1, 2, 3, 4, 5}

# Intersection
print(a & b)  # Output: {3}

# Difference
print(a - b)  # Output: {1, 2}

 

Set객체의 한계점

  • Unordered Nature
    Set는 element들을 순차적으로 저장하지 않습니다. 따라서 Index나 Slicing등은 지원하지 않습니다.
    또한 이러 특성으로, 다음과 같이 set element를 출력하는 경우, 순서가 항상 동일하지 않을수 있습니다.
    my_set = {1, 2, 3, 4, 5}
    
    for element in my_set:
        print(element)​

그럼 어떤 경우에 Set 객체를 사용하면 좋을까요?

  • Uniqueness:
    Set객체는 element가 중복되는 경우 자동으로 중복을 제거 하는 특징을 가지고 있습니다.
    즉 각 element는 하나의 Set안에서 유일합니다.
    Set의 이러한 특징을 이용해서 다음과 같은 코드가 가능합니다.
    example:
    # Original list with duplicates
    my_list = [1, 2, 2, 3, 4, 4, 5, 5, 5, 6]
    
    # Removing duplicates by converting the list to a set
    unique_set = set(my_list)
    
    # Converting back to a list
    unique_list = list(unique_set)
    
    print("Original List:", my_list)      # Output: [1, 2, 2, 3, 4, 4, 5, 5, 5, 6]
    print("List with Duplicates Removed:", unique_list)  # Output: [1, 2, 3, 4, 5, 6]
     List를 Set로 변환후 다시 List로 변환하면, 간단히 중복이 모두 제거된 List를 만들수 있습니다.

  • Efficiency:
    특정 element가 List나 Set안에 포함되어 있는지 판단 하기 위해서는 List보다 Set가 훨씬 효율적 입니다.
    # Large list and set for comparison
    total_element = 100000000
    large_list = list(range(total_element))
    large_set = set(large_list)
    
    # Testing membership
    search_element = total_element - 1
    
    # Timing membership testing in the list
    import time
    start_time = time.time()
    result_list = search_element in large_list
    end_time = time.time()
    list_search_time = end_time - start_time
    
    # Timing membership testing in the set
    start_time = time.time()
    result_set = search_element in large_set
    end_time = time.time()
    set_search_time = end_time - start_time
    
    print(f"Time taken for list: {list_search_time:.6f} seconds")
    print(f"Time taken for set: {set_search_time:.6f} seconds")
    
    # result : Time taken for list: 11.086122 seconds
    # result : Time taken for set: 0.000000 seconds

    이 코드를 실행해 보시면, List의 경우 total_element의 수에 비례하여 소요 시간은 늘어나지만, Set는 그렇지 않다는 것을 확인 할 수 있습니다.
    List는 element를 검색할때 그 요소의 처음부터 순차적으로 검색하여, O(n) 복잡도를 가지지만, 집합은 해시 테이블을 사용하여 구현됩니다.
    요소가 집합에 추가될 때 파이썬은 요소의 해시를 계산하고 해시 테이블에 저장합니다. 이 해시는 요소에 빠르게 액세스하는 데 사용됩니다. 따라서 해싱으로 인한 검색은 O(1)의 시간 복잡도를 가지며, 집합의 크기와 관계없이 일정하다는 것을 의미합니다.


  • Mathematical Operations:
    앞서 살펴본 바와 같이, Set 객체는 집합 연산을 지원 합니다.
    Operations:
    • Union (|): 합집합
    • Intersection (&): 교집합
    • Difference (-): 차집합
    • Symmetric Difference (^): 두 Set 안에 모두 포함하는 element만 제거
    • Example:
      set_a = {1, 2, 3}
      set_b = {3, 4, 5}
      
      union_set = set_a | set_b
      print(union_set)  # Output: {1, 2, 3, 4, 5}
      
      intersection_set = set_a & set_b
      print(intersection_set)  # Output: {3}
      
      difference_set = set_a - set_b
      print(difference_set)  # Output: {1, 2}
      
      symmetric_difference_set = set_a ^ set_b
      print(symmetric_difference_set)  # Output: {1, 2, 4, 5}

Set와 List 객체의 형 변환

List와 Set는 그 목적에 맞게 다음과 같이 서로 변경이 가능 합니다.

my_list = [1, 2, 2, 3, 4, 4, 5]
my_set = set(my_list)

print(my_set)  # Output: {1, 2, 3, 4, 5}

 

my_set = {1, 2, 3, 4, 5}
my_list = list(my_set)

print(my_list)  # Output: [1, 2, 3, 4, 5]

 

 

Conclusion

오늘은 Python의 Set 객체에 대해 알아 보았습니다.

 

감사합니다.

안녕하세요, 코딩 푸는 남자 입니다.!

오늘은 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값에 대한 변경은 불가능 합니다.

  1. 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'}​


  2. 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'}​


  3. 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에 대해 간단히 알아 보았습니다.

감사합니다.

 

 

 

 

 

+ Recent posts