정구리의 우주정복

[Python] Dictionary 데이터 조회방식 본문

PYTHON/STUDY

[Python] Dictionary 데이터 조회방식

Jungry_ 2025. 3. 5. 13:04
반응형

 

1. 키 (Key) 조회

키가 존재하는지 확인 (in 연산자)

my_dict = {"apple": 3, "banana": 5, "cherry": 2}

print("apple" in my_dict)  # ✅ True
print("orange" in my_dict) # ❌ False

 

  • in 연산자를 사용하면 해시 테이블을 이용해 O(1)로 빠르게 키를 검색 가능

2. 값(value) 조회

특정 값이 딕셔너리에 존재하는지 확인

print(2 in hash_map.values())

 

3. 키(key) + 값(value) 조회 (items())

모든 (key, value) 쌍을 조회할 때 O(n)

for key, value in hash_map.items():
    print(f"{key}: {value}")

 

4. 특정 값(value)을 가진 키 찾기

특정 값을 가진 키를 찾을 때 (O(n))

target_value = 2
keys_with_value = [key for key, value in hash_map.items() if value == target_value]
print(keys_with_value)

 

 

5. 키 정렬

키를 기준으로 정렬

my_dict = {"c": 3, "a": 1, "b": 2}
sorted_dict = dict(sorted(my_dict.items()))  # 키 기준 정렬
print(sorted_dict)  # ✅ {'a': 1, 'b': 2, 'c': 3}

 

값을 기준으로 정렬

sorted_by_value = dict(sorted(my_dict.items(), key=lambda x: x[1]))
print(sorted_by_value)  # ✅ {'a': 1, 'b': 2, 'c': 3}

 

6. 키 존재 여부 확인 (dict["key"] 는 없으면 에러나)

my_dict = {"a": 1, "b": 2}

# 안전한 조회 방법
print(my_dict.get("a", 0))  # ✅ 1 (존재하는 키)
print(my_dict.get("z", 0))  # ✅ 0 (존재하지 않으므로 기본값 반환)

# 존재 여부 확인
if "z" in my_dict:
    print("Exists")
반응형
Comments