Python 10: Data structure in Python

Dictionary vs Set

Set

A Set is an unordered collection data type that is iterable, mutable and has no duplicate elements.

  • List와 다르게 요소들이 순서대로 저장되어 있지 않다. 즉 ordering이 없다. 그러므로 for 문에서 읽어들일때 요소들이 순서대로 나오는게 아니라 무작위 순서대로 나옴.
  • 순서가 없으므로 indexing도 없음. 몇번째 요소를 읽어들이거나 할 수 없음.
  • 동일한 값을 가지고 있는 요소가 1개 이상 존재 할 수 없다. 즉 중복된 값을 저장할 수 없다. 만일 새로 저장하려고 하는 요소와 동일한 값의 요소가 존재한다면 새로운 요소가 이 전 요소를 치환(replace)한다. (no duplicates)

Dictionary

Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key value is provided in the dictionary to make it more optimized.

dictionary 의 가장 큰 장점은 key 와 value 로 이루어져서 data value 들을 좀 더 적합하게 저장할 수 있다는 점이다.

차이점

  • dictionarykeyvalue 값이 존재하지만 setkey 값만 존재한다.

공통점

  • 둘 다 중복된 요소를 포함하지 않는다.

Code Examples

Set

# set 구성 (key 로 구성되어있음)
{key1, key2, key3, ...}

#set 은 기본적으로 { } 으로 생성. 
my_set = {1,2,3,4,5}
print(my_set)
> {1,2,3,4,5}

# set() 함수를 사용하여 생성.
my_set = set([1,2,3,4,5])
print(my_set)
> {1,2,3,4,5}

# set 은 중복요소가 있으면 replace 된다. 
my_set = set([1,2,1,3,4,5,2,1])
print(my_set)
> {1,2,3,4,5}

Dictionary

# 새로운 딕셔너리 생성 방법 1
my_dict = {key1 : value2, key2: value2, key3 : value3}

# 새로운 딕셔너리 생성 방법 2
my_dict = {}
my_dict[key1] = value1
my_dict[key2] = value2
print(my_dict)
> {key1 : value1, key2 : value2}

Complex dictionary 예제 (Nested dictionary)

def get_team_info(team_name):
    k_league1 = { 
        "강원 FC": {
          "구단": "강원 FC",
          "리그참가": 2009,
          "연고지": "강원도(춘천시)",   
          "주 경기장": "춘천송암레포츠타운"},
        "광주 FC": {
          "구단": "광주 FC",
          "리그참가": 2011,
          "연고지": "광주광역시",   
          "주 경기장": "광주월드컵경기장"},
        "대구 FC": {
          "구단": "대구 FC",
          "리그참가": 2003,
          "연고지": "대구광역시",   
          "주 경기장": "DGB대구은행 파크"},
        "경남 FC" : {
          "구단" : "경남 FC",
          "리그참가" : 2006,
          "연고지" : "경상남도(창원시)",
          "주 경기장" : "창원축구센터"},
        "수원 삼성 블루윙즈": {
          '구단': '수원 삼성 블루윙즈',
           '리그참가': 1996,
            '연고지': '수원시',
             '주 경기장': '수원월드컵경기장'},
        "포항 스틸러스" : {
          '구단': '포항 스틸러스',
          '리그참가': 1983,
          '연고지': '포항시',
          '주 경기장': '포항스틸야드'}
        }

위와 같이 key 값을 이용해서 key값 안의 새로운 dictionary 를 생성할 수 있다. 이런 구조를 nested dictionary 라고 한다.

List vs Tuple

공통점

  • The two data structures are both sequence data types that store collections of items.
    둘 다 시퀸스 자료형(순서를 가지고 정렬되어있는) 구조를 갖고 있고 아이템들을 저장한다.
  • Items of any data type can be stored in them.
    어떤 자료형이든 저장이 가능하다.
  • Items can be accessed by their index.
    인덱스를 이용해서 접근이 가능하다.

차이점

List Tuple
Mutable
가변적
Immutable
불가변적
The implication of iterations is time-consuming in the list.
list 에선 iteration 이 돌아가는데에 시간을 많이 쓴다.
Implications of iterations are much faster in tuples.
set에선 iterations 의 시간이 훨씬 빠르다.
Operations like insertion and deletion are better performed.
`insert` 와 `delete` 같은 기능들이 훨씬 효율적이다.
(자세한 내용은 자료구조 참조해야한다.)
Elements can be accessed better.
set 에선 각 요소에게 접근이 훨씬 빠르다.
Consumes more memory.
list 는 메모리 할당량이 더 크다
Consumes less memory.
메모리 할당량이 적다
Many built-in methods are available.
빌트인 메소드가 많다.
Does not have many built-in methods.
빌트인 메소드가 많지 않다.
Unexpected errors and changes can easily occur in lists.
예상치 못한 에러와 변경이 자주 일어난다.
Unexpected errors and changes rarely occur in tuples.
에러가 잘 생기지 않는다.

Code Example

List

# Assign a list to an variable named my_list
my_list = [1,2,3]

# Checks the list length
thisList = ["apple", "banana", "cherry"]
len(thisList)
> 3

# The list() Constructor
thisList = list(("apple", "banana", "cherry"))
print(thisList)
> ["apple", "banana", "cherry"]

Tuples

# Create a tuple 튜플 생성하기
t = (1,2,3)

# Check len just like a list 튜플의 length 를 확인할 수 있다
len(t)
> 3

# Can also mix object types
t = ('one',2)

좋은 웹페이지 즐겨찾기