my_dict = {
'name': 'John',
'age': 25,
'name': 'Alice' # 'name' 키가 중복됨
}
print(my_dict) # 출력: {'name': 'Alice', 'age': 25}
person = {"name": "John", "age": 30, "city": "New York"}
#직접 인덱싱 사용
try:
print("Name:", person["name"]) # 존재하는 키
print("Salary:", person["salary"]) # 존재하지 않는 키
except KeyError:
print("KeyError: 'salary' key does not exist.")
#get() 메서드 사용
print("\nUsing get() method:")
print("Name:", person.get("name")) # 존재하는 키
print("Salary:", person.get("salary")) # 존재하지 않는 키, None을 반환
print("Salary with default:", person.get("salary", "Not Available")) # 존재하지 않는 키, 기본값 "Not Available" 반환
my_dict = {"name": "John", "age": 30, "city": "New York"}
my_dict["email"] = "john@example.com" # 새로운 키와 값 추가
my_dict["age"] = 31 # 기존 키의 값 수정
print(my_dict)
#del 키워드를 사용하여 키-값 쌍 제거
del my_dict["city"]
#pop() 메서드를 사용하여 키-값 쌍 제거 및 값 반환
age = my_dict.pop("age")
print("Removed age:", age)
#popitem() 메서드는 마지막 키-값 쌍을 제거하고 반환
item = my_dict.popitem()
print("Removed item:", item)
print(my_dict)
my_dict = {"name": "John", "age": 30, "city": "New York"}
#모든 키만 가져오기
keys = my_dict.keys()
print(keys)
#모든 값만 가져오기
values = my_dict.values()
print(values)
#모든 키-값 쌍 가져오기
items = my_dict.items()
print(items)
my_set = {1, 2, 3, 4, 5}
print(my_set)
my_set.add(6) # 요소 6 추가
print(my_set)
my_set.remove(1) # 요소 1 삭제
print(my_set)
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7}
C = {1, 5, 9}
#2. 집합 A와 B의 합집합을 구하세요.
union_AB = A.union(B)
print(union_AB)
#3. 집합 A와 C의 차집합을 구하세요.
diff_AC = A.difference(C)
print(diff_AC)
#4. 집합 A, B, C의 교집합을 구하세요.
inter_ABC = A.intersection(B, C)
print(inter_ABC)