phone_book = { } # 공백 딕셔너리를 생성
phone_book["홍길동"] = "010-1234-5678"
print(phone_book)
phone_book = {"홍길동": "010-1234-5678"}
phone_book["강감찬"] = "010-1234-5679"
phone_book["이순신"] = "010-1234-5680"
print(phone_book)
person_dic = {'Name': '홍길동', 'Age': 7, 'Class': '초급'}
print(person_dic['Name'])
print(person_dic['Age'])
print(phone_book["강감찬"])
phone_book.keys()
phone_book.values()
phone_book.items()
for name, phone_num in phone_book.items():
print(name,':', phone_num)
phone_book = {"홍길동": "010-1234-5678"}
phone_book["강감찬"] = "010-1234-5679"
phone_book["이순신"] = "010-1234-5680"
for key in phone_book.keys():
print(key, ':', phone_book[key])
sorted(phone_book) # 딕셔너리를 키를 기준으로 정렬하며 리스트를 반환
sorted_phone_book = sorted(phone_book.items(), key=lambda x: x[0])
print(sorted_phone_book)
del phone_book["홍길동"] # "홍길동" 키를 이용하여 딕셔너리의 한 항목 삭제
print(phone_book)
phone_book.clear()
print(phone_book)
items = { "커피음료": 7, "펜": 3, "종이컵": 2,
"우유": 1, "콜라": 4, "책": 5 }
item = input("물건의 이름을 입력하시오: ");
print(items[item])
print("사전 프로그램 시작... 종료는 q를 입력")
dictionary = {}
while True:
st = input('$ ')
command = st[0] # 첫 입력 문자를 추출한다
if command == '<':
st = st[1:]
inputStr = st.split(':')
if len(inputStr) < 2 :
print('입력 오류가 발생했습니다.')
else:
dictionary[inputStr[0].strip()] = inputStr[1].strip()
elif command == '>':
st = st[1:]
inputStr = st.strip()
if inputStr in dictionary:
print(dictionary[inputStr])
else :
print('{}가 사전에 없습니다.'.format(inputStr))
elif command == 'q':
break
else :
print('입력 오류가 발생했습니다.')
print("사전 프로그램을 종료합니다.")
numbers = {2, 1, 3} # 숫자 3개로 이루어진 집합 자료형
numbers
set([1, 2, 3, 1, 2]) # 리스트로부터 집합을 생성함
set("abcdefa") # 문자열도 시퀀스형이라서 집합형으로 변환이 가능하다
numbers = set() # 비어있는 집합 생성
numbers = {2, 1, 3}
if 1 in numbers: # 1이라는 항목이 numbers 집합에 있는가 검사
print("집합 안에 1이 있습니다.")
numbers = {2, 1, 3}
for x in numbers:
print(x, end=" ")
for x in sorted(numbers):
print(x, end=" ")
numbers = {1, 2, 3}
numbers.add(4)
numbers
numbers.remove(5)
numbers
a_list = ['hello', 'world', 'welcome', 'to', 'python']
'python' in a_list
A = {1, 2, 3}
B = {1, 2, 3}
A == B
A = {1, 2, 3, 4, 5}
B = {1, 2, 3}
B < A
a_set = {1, 5, 4, 3, 7, 4 } # 6개 항목으로 집합 생성
len(a_set) # 항목의 개수는 중복을 제외하면 5
max(a_set) # 항목 가운데 가장 큰 수는 7
min(a_set) # 항목 가운데 가장 작은 수는 1
sorted(a_set) # 항목을 정렬하여 리스트 만든다. 중복은 제거
sum(a_set) # 중복 원소는 하나만 사용되므로 전체 합은 20
a_set = { 1, 0, 2, 3, 3}
all(a_set), any(a_set) # a_set이 모두 True인가?, a_set에 0이 있는가? 검사
A = {1, 2, 3}
B = {3, 4, 5}
A | B # 합집합 연산
A.union(B) # 합집합 메소드
A & B # 교집합 연산
A.intersection(B) # 교집합 메소드
A - B # 차집합 연산
A.difference(B) # 차집합 메소드
A ^ B # 대칭 차집합 연산
A.symmetry_difference(B)
partyA = set(["Park", "Kim", "Lee"])
partyB = set(["Park", "Choi"])
print("2개의 파티에 모두 참석한 사람은 다음과 같습니다. ")
print ( partyA.intersection(partyB))
# 단어에서 구두점을 제거하고 소문자로 만든다.
def process(w):
output =""
for ch in w:
if( ch.isalpha() ):
output += ch
return output.lower()
words = set()
# 파일을 연다.
fname = input("입력 파일 이름: ")
file = open(fname, "r")
# 파일의 모든 줄에 대하여 반복한다.
for line in file:
lineWords = line.split()
for word in lineWords:
words.add(process(word)) # 단어를 세트에 추가한다.
print("사용된 단어의 개수=", len(words))
print(words)
num = 10
divisors = []
for i in range(2, num):
if num % i == 0:
divisors.append(i)
print(num,'의 진약수 :', divisors)
def get_divisors(num): # num의 약수를 집합형으로 반환함
divisors = set()
for i in range(2, num):
if num % i == 0:
divisors.add(i)
return divisors
x = 48
print(x,'의 진약수 :', get_divisors(x))
y = 60
print(y,'의 진약수 :', get_divisors(y))
A = get_divisors(x)
B = get_divisors(y)
print(A.intersection(B))
print(x, y,'의 최대공약수 :', max(A.intersection(B)))