1. 학습목표

2. 학습내용
# 딕셔너리!
# 딕셔너리를 파이썬에서 매우매우 중요함!
# 파이썬 엔진을 이루는 모든 데이터타입은 딕셔너리 타입을 사용하고 있음!
# 파이썬의 핵심 구현도임!
# 파이썬이 hashtable을 잘 만들어서! 딕셔너리를 고성능으로 사용할 수 있음!
# 시퀀스형
# 해시테이블 : 적은 리소스로 많은 데이터를 효율적으로 관리! 자료구조에서 매우 중요한 개념!
# 딕셔너리 : 키 중복 X
# set: 중복 허용 X
# Dict 및 Set 심화
# 중복을 허용하고 있지 않다는 것은, 같은 값이 있는지 내부적으로 검사한다는 의미!
# dict 구조
# print(__builtins__.__dict__)
"""
{'__name__': 'builtins',
'__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), '__build_class__': <built-in function __build_class__>, '__import__': <built-in function __import__>, 'abs': <built-in function abs>, 'all': <built-in function all>, 'any': <built-in function any>, 'ascii': <built-in function ascii>, 'bin': <built-in function bin>, 'breakpoint': <built-in function breakpoint>, 'callable': <built-in function callable>, 'chr': <built-in function chr>, 'compile': <built-in function compile>, 'delattr': <built-in function delattr>, 'dir': <built-in function dir>, 'divmod': <built-in function divmod>, 'eval': <built-in function eval>, 'exec': <built-in function exec>, 'format': <built-in function format>, 'getattr': <built-in function getattr>, 'globals': <built-in function globals>, 'hasattr': <built-in function hasattr>, 'hash': <built-in function hash>, 'hex': <built-in function hex>, 'id': <built-in function id>, 'input': <built-in function input>, 'isinstance': <built-in function isinstance>, 'issubclass': <built-in function issubclass>, 'iter': <built-in function iter>, 'len': <built-in function len>, 'locals': <built-in function locals>, 'max': <built-in function max>, 'min': <built-in function min>, 'next': <built-in function next>, 'oct': <built-in function oct>, 'ord': <built-in function ord>, 'pow': <built-in function pow>, 'print': <built-in function print>, 'repr': <built-in function repr>, 'round': <built-in function round>, 'setattr': <built-in function setattr>, 'sorted': <built-in function sorted>, 'sum': <built-in function sum>, 'vars': <built-in function vars>, 'None': None, 'Ellipsis': Ellipsis, 'NotImplemented': NotImplemented, 'False': False, 'True': True, 'bool': <class 'bool'>, 'memoryview': <class 'memoryview'>, 'bytearray': <class 'bytearray'>, 'bytes': <class 'bytes'>, 'classmethod': <class 'classmethod'>, 'complex': <class 'complex'>, 'dict': <class 'dict'>, 'enumerate': <class 'enumerate'>, 'filter': <class 'filter'>, 'float': <class 'float'>, 'frozenset': <class 'frozenset'>, 'property': <class 'property'>, 'int': <class 'int'>, 'list': <class 'list'>, 'map': <class 'map'>, 'object': <class 'object'>, 'range': <class 'range'>, 'reversed': <class 'reversed'>, 'set': <class 'set'>, 'slice': <class 'slice'>, 'staticmethod': <class 'staticmethod'>, 'str': <class 'str'>, 'super': <class 'super'>, 'tuple': <class 'tuple'>, 'type': <class 'type'>, 'zip': <class 'zip'>, '__debug__': True, 'BaseException': <class 'BaseException'>, 'Exception': <class 'Exception'>, 'TypeError': <class 'TypeError'>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'StopIteration': <class 'StopIteration'>, 'GeneratorExit': <class 'GeneratorExit'>, 'SystemExit': <class 'SystemExit'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'ImportError': <class 'ImportError'>, 'ModuleNotFoundError': <class 'ModuleNotFoundError'>, 'OSError': <class 'OSError'>, 'EnvironmentError': <class 'OSError'>, 'IOError': <class 'OSError'>, 'EOFError': <class 'EOFError'>, 'RuntimeError': <class 'RuntimeError'>, 'RecursionError': <class 'RecursionError'>, 'NotImplementedError': <class 'NotImplementedError'>, 'NameError': <class 'NameError'>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'AttributeError': <class 'AttributeError'>, 'SyntaxError': <class 'SyntaxError'>, 'IndentationError': <class 'IndentationError'>, 'TabError': <class 'TabError'>, 'LookupError': <class 'LookupError'>, 'IndexError': <class 'IndexError'>, 'KeyError': <class 'KeyError'>, 'ValueError': <class 'ValueError'>, 'UnicodeError': <class 'UnicodeError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'AssertionError': <class 'AssertionError'>, 'ArithmeticError': <class 'ArithmeticError'>, 'FloatingPointError': <class 'FloatingPointError'>, 'OverflowError': <class 'OverflowError'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'SystemError': <class 'SystemError'>, 'ReferenceError': <class 'ReferenceError'>, 'MemoryError': <class 'MemoryError'>, 'BufferError': <class 'BufferError'>, 'Warning': <class 'Warning'>, 'UserWarning': <class 'UserWarning'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'FutureWarning': <class 'FutureWarning'>, 'ImportWarning': <class 'ImportWarning'>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'BytesWarning': <class 'BytesWarning'>, 'ResourceWarning': <class 'ResourceWarning'>, 'ConnectionError': <class 'ConnectionError'>, 'BlockingIOError': <class 'BlockingIOError'>, 'BrokenPipeError': <class 'BrokenPipeError'>, 'ChildProcessError': <class 'ChildProcessError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'FileExistsError': <class 'FileExistsError'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'InterruptedError': <class 'InterruptedError'>, 'PermissionError': <class 'PermissionError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'TimeoutError': <class 'TimeoutError'>, 'open': <built-in function open>, 'quit': Use quit() or Ctrl-D (i.e. EOF) to exit, 'exit': Use exit() or Ctrl-D (i.e. EOF) to exit, 'copyright': Copyright (c) 2001-2018 Python Software Foundation.
All Rights Reserved.
Copyright (c) 2000 BeOpen.com.
All Rights Reserved.
Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved., 'credits': Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
for supporting Python development. See www.python.org for more information., 'license': Type license() to see the full license text, 'help': Type help() for interactive help, or help(object) for help about object.}
Process finished with exit code 0
"""
# Hash값 확인
t1 = (10, 20, (30,40,50))
t2 = (10,20,[30,40,50])
# print('EX1-2', hash(t1))
# EX1-2 5737367089334957572
# print('EX1-3', hash(t2))
"""
Traceback (most recent call last):
File "/Users/marie/PycharmProjects/untitled1/fc_lecture.py", line 40, in <module>
print('EX1-3', hash(t2))
TypeError: unhashable type: 'list'
"""
# 지능형 딕셔너리(comprehending Dict)
import csv
# 외부 CSV to List of tuple
with open('./resources/test1.csv', encoding='UTF-8') as f:
temp = csv.reader(f)
# header skip
next(temp)
NA_CODES = [tuple(x) for x in temp]
# print('EX2-1 ', NA_CODES)
# EX2-1 [('Afghanistan', 'AF'), ('Åland Islands', 'AX'), ('Albania', 'AL'), ('Algeria', 'DZ'), ('American Samoa', 'AS'), ('Andorra', 'AD'), ('Angola', 'AO'), ('Anguilla', 'AI'), ('Antarctica', 'AQ'), ('Antigua and Barbuda', 'AG'), ('Argentina', 'AR'), ('Armenia', 'AM'), ('Aruba', 'AW'), ('Australia', 'AU'), ('Austria', 'AT'), ('Azerbaijan', 'AZ'), ('Bahamas', 'BS'), ('Bahrain', 'BH'), ('Bangladesh', 'BD'), ('Barbados', 'BB'), ('Belarus', 'BY'), ('Belgium', 'BE'), ('Belize', 'BZ'), ('Benin', 'BJ'), ('Bermuda', 'BM'), ('Bhutan', 'BT'), ('Bolivia, Plurinational State of', 'BO'), ('Bonaire, Sint Eustatius and Saba', 'BQ'), ('Bosnia and Herzegovina', 'BA'), ('Botswana', 'BW'), ('Bouvet Island', 'BV'), ('Brazil', 'BR'), ('British Indian Ocean Territory', 'IO'), ('Brunei Darussalam', 'BN'), ('Bulgaria', 'BG'), ('Burkina Faso', 'BF'), ('Burundi', 'BI'), ('Cambodia', 'KH'), ('Cameroon', 'CM'), ('Canada', 'CA'), ('Cape Verde', 'CV'), ('Cayman Islands', 'KY'), ('Central African Republic', 'CF'), ('Chad', 'TD'), ('Chile', 'CL'), ('China', 'CN'), ('Christmas Island', 'CX'), ('Cocos (Keeling) Islands', 'CC'), ('Colombia', 'CO'), ('Comoros', 'KM'), ('Congo', 'CG'), ('Congo, the Democratic Republic of the', 'CD'), ('Cook Islands', 'CK'), ('Costa Rica', 'CR'), ("Côte d'Ivoire", 'CI'), ('Croatia', 'HR'), ('Cuba', 'CU'), ('Curaçao', 'CW'), ('Cyprus', 'CY'), ('Czech Republic', 'CZ'), ('Denmark', 'DK'), ('Djibouti', 'DJ'), ('Dominica', 'DM'), ('Dominican Republic', 'DO'), ('Ecuador', 'EC'), ('Egypt', 'EG'), ('El Salvador', 'SV'), ('Equatorial Guinea', 'GQ'), ('Eritrea', 'ER'), ('Estonia', 'EE'), ('Ethiopia', 'ET'), ('Falkland Islands (Malvinas)', 'FK'), ('Faroe Islands', 'FO'), ('Fiji', 'FJ'), ('Finland', 'FI'), ('France', 'FR'), ('French Guiana', 'GF'), ('French Polynesia', 'PF'), ('French Southern Territories', 'TF'), ('Gabon', 'GA'), ('Gambia', 'GM'), ('Georgia', 'GE'), ('Germany', 'DE'), ('Ghana', 'GH'), ('Gibraltar', 'GI'), ('Greece', 'GR'), ('Greenland', 'GL'), ('Grenada', 'GD'), ('Guadeloupe', 'GP'), ('Guam', 'GU'), ('Guatemala', 'GT'), ('Guernsey', 'GG'), ('Guinea', 'GN'), ('Guinea-Bissau', 'GW'), ('Guyana', 'GY'), ('Haiti', 'HT'), ('Heard Island and McDonald Islands', 'HM'), ('Holy See (Vatican City State)', 'VA'), ('Honduras', 'HN'), ('Hong Kong', 'HK'), ('Hungary', 'HU'), ('Iceland', 'IS'), ('India', 'IN'), ('Indonesia', 'ID'), ('Iran, Islamic Republic of', 'IR'), ('Iraq', 'IQ'), ('Ireland', 'IE'), ('Isle of Man', 'IM'), ('Israel', 'IL'), ('Italy', 'IT'), ('Jamaica', 'JM'), ('Japan', 'JP'), ('Jersey', 'JE'), ('Jordan', 'JO'), ('Kazakhstan', 'KZ'), ('Kenya', 'KE'), ('Kiribati', 'KI'), ("Korea, Democratic People's Republic of", 'KP'), ('Korea, Republic of', 'KR'), ('Kuwait', 'KW'), ('Kyrgyzstan', 'KG'), ("Lao People's Democratic Republic", 'LA'), ('Latvia', 'LV'), ('Lebanon', 'LB'), ('Lesotho', 'LS'), ('Liberia', 'LR'), ('Libya', 'LY'), ('Liechtenstein', 'LI'), ('Lithuania', 'LT'), ('Luxembourg', 'LU'), ('Macao', 'MO'), ('Macedonia, the Former Yugoslav Republic of', 'MK'), ('Madagascar', 'MG'), ('Malawi', 'MW'), ('Malaysia', 'MY'), ('Maldives', 'MV'), ('Mali', 'ML'), ('Malta', 'MT'), ('Marshall Islands', 'MH'), ('Martinique', 'MQ'), ('Mauritania', 'MR'), ('Mauritius', 'MU'), ('Mayotte', 'YT'), ('Mexico', 'MX'), ('Micronesia, Federated States of', 'FM'), ('Moldova, Republic of', 'MD'), ('Monaco', 'MC'), ('Mongolia', 'MN'), ('Montenegro', 'ME'), ('Montserrat', 'MS'), ('Morocco', 'MA'), ('Mozambique', 'MZ'), ('Myanmar', 'MM'), ('Namibia', 'NA'), ('Nauru', 'NR'), ('Nepal', 'NP'), ('Netherlands', 'NL'), ('New Caledonia', 'NC'), ('New Zealand', 'NZ'), ('Nicaragua', 'NI'), ('Niger', 'NE'), ('Nigeria', 'NG'), ('Niue', 'NU'), ('Norfolk Island', 'NF'), ('Northern Mariana Islands', 'MP'), ('Norway', 'NO'), ('Oman', 'OM'), ('Pakistan', 'PK'), ('Palau', 'PW'), ('Palestine, State of', 'PS'), ('Panama', 'PA'), ('Papua New Guinea', 'PG'), ('Paraguay', 'PY'), ('Peru', 'PE'), ('Philippines', 'PH'), ('Pitcairn', 'PN'), ('Poland', 'PL'), ('Portugal', 'PT'), ('Puerto Rico', 'PR'), ('Qatar', 'QA'), ('Réunion', 'RE'), ('Romania', 'RO'), ('Russian Federation', 'RU'), ('Rwanda', 'RW'), ('Saint Barthélemy', 'BL'), ('Saint Helena, Ascension and Tristan da Cunha', 'SH'), ('Saint Kitts and Nevis', 'KN'), ('Saint Lucia', 'LC'), ('Saint Martin (French part)', 'MF'), ('Saint Pierre and Miquelon', 'PM'), ('Saint Vincent and the Grenadines', 'VC'), ('Samoa', 'WS'), ('San Marino', 'SM'), ('Sao Tome and Principe', 'ST'), ('Saudi Arabia', 'SA'), ('Senegal', 'SN'), ('Serbia', 'RS'), ('Seychelles', 'SC'), ('Sierra Leone', 'SL'), ('Singapore', 'SG'), ('Sint Maarten (Dutch part)', 'SX'), ('Slovakia', 'SK'), ('Slovenia', 'SI'), ('Solomon Islands', 'SB'), ('Somalia', 'SO'), ('South Africa', 'ZA'), ('South Georgia and the South Sandwich Islands', 'GS'), ('South Sudan', 'SS'), ('Spain', 'ES'), ('Sri Lanka', 'LK'), ('Sudan', 'SD'), ('Suriname', 'SR'), ('Svalbard and Jan Mayen', 'SJ'), ('Swaziland', 'SZ'), ('Sweden', 'SE'), ('Switzerland', 'CH'), ('Syrian Arab Republic', 'SY'), ('Taiwan, Province of China', 'TW'), ('Tajikistan', 'TJ'), ('Tanzania, United Republic of', 'TZ'), ('Thailand', 'TH'), ('Timor-Leste', 'TL'), ('Togo', 'TG'), ('Tokelau', 'TK'), ('Tonga', 'TO'), ('Trinidad and Tobago', 'TT'), ('Tunisia', 'TN'), ('Turkey', 'TR'), ('Turkmenistan', 'TM'), ('Turks and Caicos Islands', 'TC'), ('Tuvalu', 'TV'), ('Uganda', 'UG'), ('Ukraine', 'UA'), ('United Arab Emirates', 'AE'), ('United Kingdom', 'GB'), ('United States', 'US'), ('United States Minor Outlying Islands', 'UM'), ('Uruguay', 'UY'), ('Uzbekistan', 'UZ'), ('Vanuatu', 'VU'), ('Venezuela, Bolivarian Republic of', 'VE'), ('Viet Nam', 'VN'), ('Virgin Islands, British', 'VG'), ('Virgin Islands, U.S.', 'VI'), ('Wallis and Futuna', 'WF'), ('Western Sahara', 'EH'), ('Yemen', 'YE'), ('Zambia', 'ZM'), ('Zimbabwe', 'ZW')]
n_code1 = {country: code for country, code in NA_CODES}
# print('EX2-2 ', n_code1)
# EX2-2 {'Afghanistan': 'AF', 'Åland Islands': 'AX', 'Albania': 'AL', 'Algeria': 'DZ', 'American Samoa': 'AS', 'Andorra': 'AD', 'Angola': 'AO', 'Anguilla': 'AI', 'Antarctica': 'AQ', 'Antigua and Barbuda': 'AG', 'Argentina': 'AR', 'Armenia': 'AM', 'Aruba': 'AW', 'Australia': 'AU', 'Austria': 'AT', 'Azerbaijan': 'AZ', 'Bahamas': 'BS', 'Bahrain': 'BH', 'Bangladesh': 'BD', 'Barbados': 'BB', 'Belarus': 'BY', 'Belgium': 'BE', 'Belize': 'BZ', 'Benin': 'BJ', 'Bermuda': 'BM', 'Bhutan': 'BT', 'Bolivia, Plurinational State of': 'BO', 'Bonaire, Sint Eustatius and Saba': 'BQ', 'Bosnia and Herzegovina': 'BA', 'Botswana': 'BW', 'Bouvet Island': 'BV', 'Brazil': 'BR', 'British Indian Ocean Territory': 'IO', 'Brunei Darussalam': 'BN', 'Bulgaria': 'BG', 'Burkina Faso': 'BF', 'Burundi': 'BI', 'Cambodia': 'KH', 'Cameroon': 'CM', 'Canada': 'CA', 'Cape Verde': 'CV', 'Cayman Islands': 'KY', 'Central African Republic': 'CF', 'Chad': 'TD', 'Chile': 'CL', 'China': 'CN', 'Christmas Island': 'CX', 'Cocos (Keeling) Islands': 'CC', 'Colombia': 'CO', 'Comoros': 'KM', 'Congo': 'CG', 'Congo, the Democratic Republic of the': 'CD', 'Cook Islands': 'CK', 'Costa Rica': 'CR', "Côte d'Ivoire": 'CI', 'Croatia': 'HR', 'Cuba': 'CU', 'Curaçao': 'CW', 'Cyprus': 'CY', 'Czech Republic': 'CZ', 'Denmark': 'DK', 'Djibouti': 'DJ', 'Dominica': 'DM', 'Dominican Republic': 'DO', 'Ecuador': 'EC', 'Egypt': 'EG', 'El Salvador': 'SV', 'Equatorial Guinea': 'GQ', 'Eritrea': 'ER', 'Estonia': 'EE', 'Ethiopia': 'ET', 'Falkland Islands (Malvinas)': 'FK', 'Faroe Islands': 'FO', 'Fiji': 'FJ', 'Finland': 'FI', 'France': 'FR', 'French Guiana': 'GF', 'French Polynesia': 'PF', 'French Southern Territories': 'TF', 'Gabon': 'GA', 'Gambia': 'GM', 'Georgia': 'GE', 'Germany': 'DE', 'Ghana': 'GH', 'Gibraltar': 'GI', 'Greece': 'GR', 'Greenland': 'GL', 'Grenada': 'GD', 'Guadeloupe': 'GP', 'Guam': 'GU', 'Guatemala': 'GT', 'Guernsey': 'GG', 'Guinea': 'GN', 'Guinea-Bissau': 'GW', 'Guyana': 'GY', 'Haiti': 'HT', 'Heard Island and McDonald Islands': 'HM', 'Holy See (Vatican City State)': 'VA', 'Honduras': 'HN', 'Hong Kong': 'HK', 'Hungary': 'HU', 'Iceland': 'IS', 'India': 'IN', 'Indonesia': 'ID', 'Iran, Islamic Republic of': 'IR', 'Iraq': 'IQ', 'Ireland': 'IE', 'Isle of Man': 'IM', 'Israel': 'IL', 'Italy': 'IT', 'Jamaica': 'JM', 'Japan': 'JP', 'Jersey': 'JE', 'Jordan': 'JO', 'Kazakhstan': 'KZ', 'Kenya': 'KE', 'Kiribati': 'KI', "Korea, Democratic People's Republic of": 'KP', 'Korea, Republic of': 'KR', 'Kuwait': 'KW', 'Kyrgyzstan': 'KG', "Lao People's Democratic Republic": 'LA', 'Latvia': 'LV', 'Lebanon': 'LB', 'Lesotho': 'LS', 'Liberia': 'LR', 'Libya': 'LY', 'Liechtenstein': 'LI', 'Lithuania': 'LT', 'Luxembourg': 'LU', 'Macao': 'MO', 'Macedonia, the Former Yugoslav Republic of': 'MK', 'Madagascar': 'MG', 'Malawi': 'MW', 'Malaysia': 'MY', 'Maldives': 'MV', 'Mali': 'ML', 'Malta': 'MT', 'Marshall Islands': 'MH', 'Martinique': 'MQ', 'Mauritania': 'MR', 'Mauritius': 'MU', 'Mayotte': 'YT', 'Mexico': 'MX', 'Micronesia, Federated States of': 'FM', 'Moldova, Republic of': 'MD', 'Monaco': 'MC', 'Mongolia': 'MN', 'Montenegro': 'ME', 'Montserrat': 'MS', 'Morocco': 'MA', 'Mozambique': 'MZ', 'Myanmar': 'MM', 'Namibia': 'NA', 'Nauru': 'NR', 'Nepal': 'NP', 'Netherlands': 'NL', 'New Caledonia': 'NC', 'New Zealand': 'NZ', 'Nicaragua': 'NI', 'Niger': 'NE', 'Nigeria': 'NG', 'Niue': 'NU', 'Norfolk Island': 'NF', 'Northern Mariana Islands': 'MP', 'Norway': 'NO', 'Oman': 'OM', 'Pakistan': 'PK', 'Palau': 'PW', 'Palestine, State of': 'PS', 'Panama': 'PA', 'Papua New Guinea': 'PG', 'Paraguay': 'PY', 'Peru': 'PE', 'Philippines': 'PH', 'Pitcairn': 'PN', 'Poland': 'PL', 'Portugal': 'PT', 'Puerto Rico': 'PR', 'Qatar': 'QA', 'Réunion': 'RE', 'Romania': 'RO', 'Russian Federation': 'RU', 'Rwanda': 'RW', 'Saint Barthélemy': 'BL', 'Saint Helena, Ascension and Tristan da Cunha': 'SH', 'Saint Kitts and Nevis': 'KN', 'Saint Lucia': 'LC', 'Saint Martin (French part)': 'MF', 'Saint Pierre and Miquelon': 'PM', 'Saint Vincent and the Grenadines': 'VC', 'Samoa': 'WS', 'San Marino': 'SM', 'Sao Tome and Principe': 'ST', 'Saudi Arabia': 'SA', 'Senegal': 'SN', 'Serbia': 'RS', 'Seychelles': 'SC', 'Sierra Leone': 'SL', 'Singapore': 'SG', 'Sint Maarten (Dutch part)': 'SX', 'Slovakia': 'SK', 'Slovenia': 'SI', 'Solomon Islands': 'SB', 'Somalia': 'SO', 'South Africa': 'ZA', 'South Georgia and the South Sandwich Islands': 'GS', 'South Sudan': 'SS', 'Spain': 'ES', 'Sri Lanka': 'LK', 'Sudan': 'SD', 'Suriname': 'SR', 'Svalbard and Jan Mayen': 'SJ', 'Swaziland': 'SZ', 'Sweden': 'SE', 'Switzerland': 'CH', 'Syrian Arab Republic': 'SY', 'Taiwan, Province of China': 'TW', 'Tajikistan': 'TJ', 'Tanzania, United Republic of': 'TZ', 'Thailand': 'TH', 'Timor-Leste': 'TL', 'Togo': 'TG', 'Tokelau': 'TK', 'Tonga': 'TO', 'Trinidad and Tobago': 'TT', 'Tunisia': 'TN', 'Turkey': 'TR', 'Turkmenistan': 'TM', 'Turks and Caicos Islands': 'TC', 'Tuvalu': 'TV', 'Uganda': 'UG', 'Ukraine': 'UA', 'United Arab Emirates': 'AE', 'United Kingdom': 'GB', 'United States': 'US', 'United States Minor Outlying Islands': 'UM', 'Uruguay': 'UY', 'Uzbekistan': 'UZ', 'Vanuatu': 'VU', 'Venezuela, Bolivarian Republic of': 'VE', 'Viet Nam': 'VN', 'Virgin Islands, British': 'VG', 'Virgin Islands, U.S.': 'VI', 'Wallis and Futuna': 'WF', 'Western Sahara': 'EH', 'Yemen': 'YE', 'Zambia': 'ZM', 'Zimbabwe': 'ZW'}
n_code2 = {country.upper(): code for country, code in NA_CODES}
# print('EX2-3 ', n_code2)
# EX2-3 {'AFGHANISTAN': 'AF', 'ÅLAND ISLANDS': 'AX', 'ALBANIA': 'AL', 'ALGERIA': 'DZ', 'AMERICAN SAMOA': 'AS', 'ANDORRA': 'AD', 'ANGOLA': 'AO', 'ANGUILLA': 'AI', 'ANTARCTICA': 'AQ', 'ANTIGUA AND BARBUDA': 'AG', 'ARGENTINA': 'AR', 'ARMENIA': 'AM', 'ARUBA': 'AW', 'AUSTRALIA': 'AU', 'AUSTRIA': 'AT', 'AZERBAIJAN': 'AZ', 'BAHAMAS': 'BS', 'BAHRAIN': 'BH', 'BANGLADESH': 'BD', 'BARBADOS': 'BB', 'BELARUS': 'BY', 'BELGIUM': 'BE', 'BELIZE': 'BZ', 'BENIN': 'BJ', 'BERMUDA': 'BM', 'BHUTAN': 'BT', 'BOLIVIA, PLURINATIONAL STATE OF': 'BO', 'BONAIRE, SINT EUSTATIUS AND SABA': 'BQ', 'BOSNIA AND HERZEGOVINA': 'BA', 'BOTSWANA': 'BW', 'BOUVET ISLAND': 'BV', 'BRAZIL': 'BR', 'BRITISH INDIAN OCEAN TERRITORY': 'IO', 'BRUNEI DARUSSALAM': 'BN', 'BULGARIA': 'BG', 'BURKINA FASO': 'BF', 'BURUNDI': 'BI', 'CAMBODIA': 'KH', 'CAMEROON': 'CM', 'CANADA': 'CA', 'CAPE VERDE': 'CV', 'CAYMAN ISLANDS': 'KY', 'CENTRAL AFRICAN REPUBLIC': 'CF', 'CHAD': 'TD', 'CHILE': 'CL', 'CHINA': 'CN', 'CHRISTMAS ISLAND': 'CX', 'COCOS (KEELING) ISLANDS': 'CC', 'COLOMBIA': 'CO', 'COMOROS': 'KM', 'CONGO': 'CG', 'CONGO, THE DEMOCRATIC REPUBLIC OF THE': 'CD', 'COOK ISLANDS': 'CK', 'COSTA RICA': 'CR', "CÔTE D'IVOIRE": 'CI', 'CROATIA': 'HR', 'CUBA': 'CU', 'CURAÇAO': 'CW', 'CYPRUS': 'CY', 'CZECH REPUBLIC': 'CZ', 'DENMARK': 'DK', 'DJIBOUTI': 'DJ', 'DOMINICA': 'DM', 'DOMINICAN REPUBLIC': 'DO', 'ECUADOR': 'EC', 'EGYPT': 'EG', 'EL SALVADOR': 'SV', 'EQUATORIAL GUINEA': 'GQ', 'ERITREA': 'ER', 'ESTONIA': 'EE', 'ETHIOPIA': 'ET', 'FALKLAND ISLANDS (MALVINAS)': 'FK', 'FAROE ISLANDS': 'FO', 'FIJI': 'FJ', 'FINLAND': 'FI', 'FRANCE': 'FR', 'FRENCH GUIANA': 'GF', 'FRENCH POLYNESIA': 'PF', 'FRENCH SOUTHERN TERRITORIES': 'TF', 'GABON': 'GA', 'GAMBIA': 'GM', 'GEORGIA': 'GE', 'GERMANY': 'DE', 'GHANA': 'GH', 'GIBRALTAR': 'GI', 'GREECE': 'GR', 'GREENLAND': 'GL', 'GRENADA': 'GD', 'GUADELOUPE': 'GP', 'GUAM': 'GU', 'GUATEMALA': 'GT', 'GUERNSEY': 'GG', 'GUINEA': 'GN', 'GUINEA-BISSAU': 'GW', 'GUYANA': 'GY', 'HAITI': 'HT', 'HEARD ISLAND AND MCDONALD ISLANDS': 'HM', 'HOLY SEE (VATICAN CITY STATE)': 'VA', 'HONDURAS': 'HN', 'HONG KONG': 'HK', 'HUNGARY': 'HU', 'ICELAND': 'IS', 'INDIA': 'IN', 'INDONESIA': 'ID', 'IRAN, ISLAMIC REPUBLIC OF': 'IR', 'IRAQ': 'IQ', 'IRELAND': 'IE', 'ISLE OF MAN': 'IM', 'ISRAEL': 'IL', 'ITALY': 'IT', 'JAMAICA': 'JM', 'JAPAN': 'JP', 'JERSEY': 'JE', 'JORDAN': 'JO', 'KAZAKHSTAN': 'KZ', 'KENYA': 'KE', 'KIRIBATI': 'KI', "KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF": 'KP', 'KOREA, REPUBLIC OF': 'KR', 'KUWAIT': 'KW', 'KYRGYZSTAN': 'KG', "LAO PEOPLE'S DEMOCRATIC REPUBLIC": 'LA', 'LATVIA': 'LV', 'LEBANON': 'LB', 'LESOTHO': 'LS', 'LIBERIA': 'LR', 'LIBYA': 'LY', 'LIECHTENSTEIN': 'LI', 'LITHUANIA': 'LT', 'LUXEMBOURG': 'LU', 'MACAO': 'MO', 'MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF': 'MK', 'MADAGASCAR': 'MG', 'MALAWI': 'MW', 'MALAYSIA': 'MY', 'MALDIVES': 'MV', 'MALI': 'ML', 'MALTA': 'MT', 'MARSHALL ISLANDS': 'MH', 'MARTINIQUE': 'MQ', 'MAURITANIA': 'MR', 'MAURITIUS': 'MU', 'MAYOTTE': 'YT', 'MEXICO': 'MX', 'MICRONESIA, FEDERATED STATES OF': 'FM', 'MOLDOVA, REPUBLIC OF': 'MD', 'MONACO': 'MC', 'MONGOLIA': 'MN', 'MONTENEGRO': 'ME', 'MONTSERRAT': 'MS', 'MOROCCO': 'MA', 'MOZAMBIQUE': 'MZ', 'MYANMAR': 'MM', 'NAMIBIA': 'NA', 'NAURU': 'NR', 'NEPAL': 'NP', 'NETHERLANDS': 'NL', 'NEW CALEDONIA': 'NC', 'NEW ZEALAND': 'NZ', 'NICARAGUA': 'NI', 'NIGER': 'NE', 'NIGERIA': 'NG', 'NIUE': 'NU', 'NORFOLK ISLAND': 'NF', 'NORTHERN MARIANA ISLANDS': 'MP', 'NORWAY': 'NO', 'OMAN': 'OM', 'PAKISTAN': 'PK', 'PALAU': 'PW', 'PALESTINE, STATE OF': 'PS', 'PANAMA': 'PA', 'PAPUA NEW GUINEA': 'PG', 'PARAGUAY': 'PY', 'PERU': 'PE', 'PHILIPPINES': 'PH', 'PITCAIRN': 'PN', 'POLAND': 'PL', 'PORTUGAL': 'PT', 'PUERTO RICO': 'PR', 'QATAR': 'QA', 'RÉUNION': 'RE', 'ROMANIA': 'RO', 'RUSSIAN FEDERATION': 'RU', 'RWANDA': 'RW', 'SAINT BARTHÉLEMY': 'BL', 'SAINT HELENA, ASCENSION AND TRISTAN DA CUNHA': 'SH', 'SAINT KITTS AND NEVIS': 'KN', 'SAINT LUCIA': 'LC', 'SAINT MARTIN (FRENCH PART)': 'MF', 'SAINT PIERRE AND MIQUELON': 'PM', 'SAINT VINCENT AND THE GRENADINES': 'VC', 'SAMOA': 'WS', 'SAN MARINO': 'SM', 'SAO TOME AND PRINCIPE': 'ST', 'SAUDI ARABIA': 'SA', 'SENEGAL': 'SN', 'SERBIA': 'RS', 'SEYCHELLES': 'SC', 'SIERRA LEONE': 'SL', 'SINGAPORE': 'SG', 'SINT MAARTEN (DUTCH PART)': 'SX', 'SLOVAKIA': 'SK', 'SLOVENIA': 'SI', 'SOLOMON ISLANDS': 'SB', 'SOMALIA': 'SO', 'SOUTH AFRICA': 'ZA', 'SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS': 'GS', 'SOUTH SUDAN': 'SS', 'SPAIN': 'ES', 'SRI LANKA': 'LK', 'SUDAN': 'SD', 'SURINAME': 'SR', 'SVALBARD AND JAN MAYEN': 'SJ', 'SWAZILAND': 'SZ', 'SWEDEN': 'SE', 'SWITZERLAND': 'CH', 'SYRIAN ARAB REPUBLIC': 'SY', 'TAIWAN, PROVINCE OF CHINA': 'TW', 'TAJIKISTAN': 'TJ', 'TANZANIA, UNITED REPUBLIC OF': 'TZ', 'THAILAND': 'TH', 'TIMOR-LESTE': 'TL', 'TOGO': 'TG', 'TOKELAU': 'TK', 'TONGA': 'TO', 'TRINIDAD AND TOBAGO': 'TT', 'TUNISIA': 'TN', 'TURKEY': 'TR', 'TURKMENISTAN': 'TM', 'TURKS AND CAICOS ISLANDS': 'TC', 'TUVALU': 'TV', 'UGANDA': 'UG', 'UKRAINE': 'UA', 'UNITED ARAB EMIRATES': 'AE', 'UNITED KINGDOM': 'GB', 'UNITED STATES': 'US', 'UNITED STATES MINOR OUTLYING ISLANDS': 'UM', 'URUGUAY': 'UY', 'UZBEKISTAN': 'UZ', 'VANUATU': 'VU', 'VENEZUELA, BOLIVARIAN REPUBLIC OF': 'VE', 'VIET NAM': 'VN', 'VIRGIN ISLANDS, BRITISH': 'VG', 'VIRGIN ISLANDS, U.S.': 'VI', 'WALLIS AND FUTUNA': 'WF', 'WESTERN SAHARA': 'EH', 'YEMEN': 'YE', 'ZAMBIA': 'ZM', 'ZIMBABWE': 'ZW'}
# Dict Setdefault 예제
source = (
('k1', 'val1'),
('k1', 'val2'),
('k2', 'val3'),
('k2', 'val4'),
('k2', 'val5')
)
new_dict1 = {}
# No use setdefault
for k, v in source:
if k in new_dict1:
new_dict1[k].append(v)
else:
new_dict1[k] = [v]
# print('EX3-1 -', new_dict1)
# EX3-1 - {'k1': ['val1', 'val2'], 'k2': ['val3', 'val4', 'val5']}
# Use Setdefault
new_dict2 = {}
for k, v in source:
new_dict2.setdefault(k, []).append(v)
# print('EX3-2 -', new_dict2)
# EX3-2 - {'k1': ['val1', 'val2'], 'k2': ['val3', 'val4', 'val5']}
# 사용자 정의 dict 상속(UserDict 가능)
class UserDict(dict):
def __missing__(self, key):
print('Called: __missing__')
if isinstance(key, str):
raise KeyError(key)
return self[str(key)]
def get(self, key, default=None):
print('Called : __getitem___')
try:
return self[key]
except KeyError:
return default
def __contains__(self, key):
print('Called : __continas__')
return key in self.keys() or str(key) in self.keys()
user_dict1 = UserDict(one = 1, two = 2)
user_dict2 = UserDict({'one': 1, 'two': 2})
user_dict3 = UserDict([('one', 1), ('two', 2)])
# print('EX4-1 -', user_dict1)
# EX4-1 - {'one': 1, 'two': 2}
# print('EX4-2 -', user_dict2)
# EX4-2 - {'one': 1, 'two': 2}
# print('EX4-3 -', user_dict3)
# EX4-3 - {'one': 1, 'two': 2}
# print('EX4-4 -', user_dict2.get('two'))
"""
Called : __getitem___
EX4-4 - 2
"""
# print('EX4-5 -', user_dict2.get('aaa'))
"""
Called : __getitem___
Called: __missing__
EX4-5 - None
"""
# print('EX4-5 -', 'one' in user_dict3)
"""
Called : __continas__
EX4-5 - True
"""
# print('EX4-6 -', user_dict3['there'])
"""
Traceback (most recent call last):
File "/Users/marie/PycharmProjects/untitled1/fc_lecture.py", line 148, in <module>
print('EX4-6 -', user_dict3['there'])
File "/Users/marie/PycharmProjects/untitled1/fc_lecture.py", line 102, in __missing__
raise KeyError(key)
KeyError: 'there'
Called: __missing__
"""
# print('EX4-7 -', user_dict3.get('there'))
"""
Called : __getitem___
Called: __missing__
EX4-7 - None
"""
# print('EX4-8 -', 'there' in user_dict3)
"""
Called : __continas__
EX4-8 - False
"""
# immutable Dict
# 딕셔너리를 원래 mutable(수정가능)
from types import MappingProxyType
d = {'key1':'TEST1'}
# READ ONLY
d_frozen = MappingProxyType(d)
# print('EX5-1- ', d, id(d))
# EX5-1- {'key1': 'TEST1'} 4319974528
# print('EX5-2- ', d_frozen, id(d_frozen))
# EX5-2- {'key1': 'TEST1'} 4339182376
# print('EX5-3- ', d is d_frozen, d == d_frozen)
# EX5-3- False True
# 수정/추가 불가
# d_frozen['key1'] = 'TEST2'
"""
Traceback (most recent call last):
File "/Users/marie/PycharmProjects/untitled1/fc_lecture.py", line 19, in <module>
d_frozen['key1'] = 'TEST2'
TypeError: 'mappingproxy' object does not support item assignment
"""
# SET 구조(FrozenSet)
s1 = {'Apple', 'Orange', 'Apple', 'Orange', 'Kiwi'}
s2 = set(['Apple', 'Orange', 'Apple', 'Orange', 'Kiwi'])
s3 = {3}
s4 = set() # 아무것도 없는 set 만들기
s5 = frozenset({'Apple', 'Orange', 'Apple', 'Orange', 'Kiwi'})
# 추가
s1.add('Melon')
# print(s1, type(s1))
# {'Kiwi', 'Melon', 'Apple', 'Orange'} <class 'set'>
# 추가불가
# s5.add('Melon')
"""
Traceback (most recent call last):
File "/Users/marie/PycharmProjects/untitled1/fc_lecture.py", line 43, in <module>
s5.add('Melon')
AttributeError: 'frozenset' object has no attribute 'add'
"""
# print(s5, type(s5))
# frozenset({'Kiwi', 'Orange', 'Apple'}) <class 'frozenset'>
# 선언 최적화
# a,b 중 a 방법이 더 빠름!
a = {5}
b = set([10])
from dis import dis
# print(dis('{10}'))
"""
1 0 LOAD_CONST 0 (10)
2 BUILD_SET 1
4 RETURN_VALUE
None
"""
# print(dis('set([10])'))
"""
1 0 LOAD_NAME 0 (set)
2 LOAD_CONST 0 (10)
4 BUILD_LIST 1
6 CALL_FUNCTION 1
8 RETURN_VALUE
None
"""
# 지능형 집합(comprehending set)
from unicodedata import name
# print({chr(i) for i in range(0,50)})
# {'\x01', '\x00', '\x13', '\x11', '\x19', '%', '\x02', '\x1e', ')', '1', ',', '\x0c', '-', '(', "'", '\x1c', '+', '\x03', '&', '\x04', '\x1f', '\x08', '\x17', '!', '\x1a', '\x12', '#', '\x14', '\x0b', '\x16', '\x1b', '\n', '\t', '\x0e', '\x07', '\x18', '*', '\x0f', '"', '.', '\x06', '\x1d', '/', '$', '\x15', ' ', '\x05', '0', '\r', '\x10'}
# print({name(chr(i), '') for i in range(0,50)})
# {'', 'LEFT PARENTHESIS', 'QUOTATION MARK', 'DOLLAR SIGN', 'EXCLAMATION MARK', 'DIGIT ZERO', 'ASTERISK', 'RIGHT PARENTHESIS', 'SPACE', 'COMMA', 'PERCENT SIGN', 'APOSTROPHE', 'DIGIT ONE', 'PLUS SIGN', 'SOLIDUS', 'AMPERSAND', 'HYPHEN-MINUS', 'NUMBER SIGN', 'FULL STOP'}
3. 느낀 점