1. 딕셔너리(Dictionary)

  • { key : value }로 표현한다.
  • 대응관계를 나타내는 자료형이다.
  • keyvalue에 다양하 자료형을 넣을 수 있다.
    숫자, 문자, 리스트, 튜플, 딕셔너리, 참/거짓, None 모두 가능
  • `key`는 중복될 수 없다.
  • dict(a): a를 딕셔너리형으로 변환한다.

1) 딕셔너리 만들기

  1. {key1:value1, key2:value2, ...}
  2. dict([(key1,value1), (key2,value2),...])
    (튜플, 리스트 바꿔도 가능)
  3. dict(zip([key1, key2, ...], [value1, value2, ...]))
    (튜플, 리스트 모두 가능)

zip(a, b)는 a와 b의 같은 위치에 있는 요소를 하나로 묶어 주는 기능을 한다.

coffee1 = {'americano':4400, 'latte':5000, 'cappuccino':5300}
coffee2 = dict([('americano',4400), ('latte',5000), ('cappuccino',5300)])
coffee3 = dict(zip(['americano','latte','cappuccino'],[4400,5000,5300]))

print('type >',type(coffee1))
print('coffee1',coffee1)
print('coffee2',coffee2)
print('coffee3',coffee3)
type > <class 'dict'>
coffee1 {'americano': 4400, 'latte': 5000, 'cappuccino': 5300}
coffee2 {'americano': 4400, 'latte': 5000, 'cappuccino': 5300}
coffee3 {'americano': 4400, 'latte': 5000, 'cappuccino': 5300}

2) Key / Value 찾기

함수 설명
a.keys() 딕셔너리 akey들을 반환한다
a.values() 딕셔너리 avalue들을 반환한다
a.itmes() 딕셔너리 a쌍(key,value)들을 반환한다
a['key1'] 딕셔너리 a에서 `key1`에 해당하는 value를 반환한다
a.get('key1') 딕셔너리 a에서 `key1`에 해당하는 value를 반환한다

a['key1']a.get('key1')의 기능은 같지만,
     딕셔너리에 'key1'이 없을 때
     전자는 Error가 나오고, 후자는 None이 출력된다.

coffee = {'americano':4400, 'latte':5000, 'cappuccino':5300}

print(coffee.keys())             # 딕셔너리의 모든 key 출력
print(coffee.values())           # 딕셔너리의 모든 value 출력'
print(coffee.items())            # 딕셔너리의 모든 쌍 출력
print(coffee['latte'])           # value 찾기 
print(coffee.get('cappuccino'))  # value 찾기
print(coffee.get('cefe mocha'))  # key가 없을 때
print(coffee['cefe mocha'])      # key가 없을 때(Error)
dict_keys(['americano', 'latte', 'cappuccino'])
dict_values([4400, 5000, 5300])
dict_items([('americano', 4400), ('latte', 5000), ('cappuccino', 5300)])
5000
5300
None

3) 추가 / 수정 / 제거

coffee = {'americano':4400, 'latte':5000, 'cappuccino':5300}

coffee['cafe mocha'] = 5300
print('추가 >',coffee)

coffee['americano'] = 3000
print('수정 >',coffee)

del coffee['latte']
print('제거 >',coffee)

coffee.clear()
print('모두 제거',coffee)
추가 > {'americano': 4400, 'latte': 5000, 'cappuccino': 5300, 'cafe mocha': 5300}
수정 > {'americano': 3000, 'latte': 5000, 'cappuccino': 5300, 'cafe mocha': 5300}
제거 > {'americano': 3000, 'cappuccino': 5300, 'cafe mocha': 5300}
모두 제거 > {}

2. 참과 거짓(True / False)

  • bool(a): a를 참/거짓형으로 변환한다.
  • True : 1, 문자, 숫자, space(' '), escape code(enter(\n), tab(\t))
  • False : 0, 공백(''), None

1) and / or

  • and, 교집합으로 둘 다 만족해야 한다.
  • or, 합집합으로 둘 중 하나만 만족해도 된다.
  • A and B : A와 B가 둘다 True이면 B를, False이면 A를 출력한다.
  • A or B : A와 B가 둘다 True이면 A를, False이면 B를 출력한다.

    A and B Result Print   A or B Result Print
    True and True True B | True or True True A
    False and True False A | False or True True B
    True and False False B | True or False True A
    False and False False A | False or False False B
print('True  and True  >', 'Result:', True  and True , '> Print:', 'Hi' and 1)
print('False and True  >', 'Result:', False and True , '> Print:', 0 and 1)
print('True  and False >', 'Result:', True  and False, '> Print:', 1 and 0)
print('False and False >', 'Result:', False and False, '> Print:', False and 0)
print('-'*50)
print('True  or  True  >', 'Result:', True  or  True , '> Print:', 'Hi' or  1)
print('False or  True  >', 'Result:', False or  True , '> Print:', 0 or  1)
print('True  or  False >', 'Result:', True  or  False, '> Print:', 1 or  0)
print('False or  False >', 'Result:', False or  False, '> Print:', False or 0)
True  and True  > Result: True > Print: 1
False and True  > Result: False > Print: 0
True  and False > Result: False > Print: 0
False and False > Result: False > Print: False
--------------------------------------------------
True  or  True  > Result: True > Print: Hi
False or  True  > Result: True > Print: 1
True  or  False > Result: True > Print: 1

2) 요소가 있는지 확인

# 리스트(list), 튜플(tuple)도 동일
a = list(range(1, 10, 2))
print(a)

print('1이 a안에 있는가? >', 1 in a)
print('1이 a안에 있지 않는가? >', 1 not in a)

print('-' * 50)

# 딕셔너리(dictionary)
student = {'name':'Hong gil dong', 'age':24, 'grade':2}
print(student)

print('"name"이 student안에 있는가? >', 'name' in student)
print('"address"가 student안에 있는가? >', 'address' in student)
[1, 3, 5, 7, 9]
1이 a안에 있는가? > True
1이 a안에 있지 않는가? > False
--------------------------------------------------
{'name': 'Hong gil dong', 'age': 24, 'grade': 2}
"name"이 student안에 있는가? > True
"address"가 student안에 있는가? > False

3. 변수(Variance)

변수는 하나의 객체(Object)이다.

객체(Object)란?
하나의 데이터로 메모리의 한 공간을 차지하며 주소(id)를 갖는다.
(나는 대한민국을 메모리 공간, 새로 태어난 아이를 객체, 아이의 주민등록번호를 주소라고 비유해서 이해했다.)

  • =을 통해 변수에 값을 할당한다.
  • 여러 개의 변수를 한 줄로 할당할 수 있다. (Python만 가능)
      a, b, c = ['대한', '민국', '만세']
      print('a >', a, '| b >', b, '| c >', c)
    
      a > 대한 | b > 민국 | c > 만세
    
  • b = a의 의미는 객체 `b`가 객체 `a`를 복사한 것이 아니다.
    같은 주소(id)를 공유한다. 따라서 b를 수정하면 a도 수정된다.
    (내가 이해한대로 해석하면 b와 a는 동일한 아이인 것이다.)
  • 같은 주소(id)를 공유하는지 확인하고 싶을 때는 is를 통해 True/False를 확인한다.
    a == b는 내용이 같은지 확인하고,
        a is b는 주소(id)가 같은지를 확인한다.
  • a의 내용만 복사해오고 싶다면 .copy()함수를 이용해야 한다.
    (즉, 동명이인을 만들고 싶은 것이다.)
# 객체 할당
a = {'name': 'Hong Gil dong', 'birth': '2012-05-15', 'sex':'male'}
b = a
print('a >', a)
print('b >', b)
print('a is b ?', a is b, '| a == b ?', a == b)
print('a의 주소 >', id(a), '| b의 주소 >', id(b))
print('-'*50)

# b 수정
b['birth'] = '2020-12-31'
print('a >', a)
print('b >', b)
print('a is b ?', a is b, '| a == b ?', a == b)
print('a의 주소 >', id(a), '| b의 주소 >', id(b))
print('-'*50)

# a를 복사해서 c 생성
c = a.copy()
print('a >', a)
print('c >', b)
print('a is c ?', a is c, '| a == c ?', a == c)
print('a의 주소 >', id(a), '| c의 주소 >', id(c))
print('-'*50)

# c 수정
c['birth'] = '2020-12-31'
print('a >', a)
print('c >', c)
print('a is c ?', a is c, '| a == c ?', a == c)
print('a의 주소 >', id(a), '| c의 주소 >', id(c))
print('-'*50)
a > {'name': 'Hong Gil dong', 'birth': '2012-05-15', 'sex': 'male'}
b > {'name': 'Hong Gil dong', 'birth': '2012-05-15', 'sex': 'male'}
a is b ? True | a == b ? True
a의 주소 > 1902993392576 | b의 주소 > 1902993392576
--------------------------------------------------
a > {'name': 'Hong Gil dong', 'birth': '2020-12-31', 'sex': 'male'}
b > {'name': 'Hong Gil dong', 'birth': '2020-12-31', 'sex': 'male'}
a is b ? True | a == b ? True
a의 주소 > 1902993392576 | b의 주소 > 1902993392576
--------------------------------------------------
a > {'name': 'Hong Gil dong', 'birth': '2020-12-31', 'sex': 'male'}
c > {'name': 'Hong Gil dong', 'birth': '2020-12-31', 'sex': 'male'}
a is c ? False | a == c ? True
a의 주소 > 1902993392576 | c의 주소 > 1902993393856
--------------------------------------------------
a > {'name': 'Hong Gil dong', 'birth': '2020-12-31', 'sex': 'male'}
c > {'name': 'Hong Gil dong', 'birth': '2020-12-31', 'sex': 'male'}
a is c ? False | a == c ? True
a의 주소 > 1902993392576 | c의 주소 > 1902993393856
--------------------------------------------------

n차원 리스트의 복사(deepcopy())

  • import copy를 실행해주어야 한다.
  • copy.deepcopy(lst)로 안의 리스트들까지 copy할 수 있다.
  • 처음 리스트는 copy되지만, 그 안의 리스트는 copy되지 않는다.

      # a 복사(copy 이용)
      a = [[10, 20], [30, 40], [50, 60]]
    
      b = a.copy()
      b[0] = [1, 2]
      b[1][0] = 999
    
      print('a >', a)
      print('b >', b)
    
      # 1차원 요소의 주소
      print('a 주소 >', [id(i) for i in a])
      print('b 주소 >', [id(i) for i in b])
    
      # 2차원 요소의 주소
      print('a[1] 주소 >', [id(i) for i in a[1]])
      print('b[1] 주소 >', [id(i) for i in b[1]])
    
      print('-'*70)
    
      # a 복사(deepcopy 이용)
      a = [[10, 20], [30, 40], [50, 60]]
    
      import copy
      c = copy.deepcopy(a)
      c[0] = [1, 2]
      c[1][0] = 999
    
      print('a >', a)
      print('c >', c)
    
      # 1차원 요소의 주소
      print('a 주소 >', [id(i) for i in a])
      print('c 주소 >', [id(i) for i in c])
    
      # 2차원 요소의 주소
      print('a[1] 주소 >', [id(i) for i in a[1]])
      print('c[1] 주소 >', [id(i) for i in c[1]])
    
      a > [[10, 20], [999, 40], [50, 60]]
      b > [[1, 2], [999, 40], [50, 60]]
      a 주소 > [1902993689920, 1902993697792, 1902993692160]
      b 주소 > [1902989300864, 1902993697792, 1902993692160]
      a[1] 주소 > [1902996271248, 1902900872656]
      b[1] 주소 > [1902996271248, 1902900872656]
      ----------------------------------------------------------------------
      a > [[10, 20], [30, 40], [50, 60]]
      c > [[1, 2], [999, 40], [50, 60]]
      a 주소 > [1902993000640, 1902993391680, 1902993697088]
      c 주소 > [1902993507520, 1902993696832, 1902993396672]
      a[1] 주소 > [1902900872336, 1902900872656]
      c[1] 주소 > [1902996272656, 1902900872656]
    

Reference

댓글남기기