본문 바로가기
etc.

[Java/Python] 문법 비교 정리 #7 자료구조 - HashMap(Dictionary)

by Lee David 2022. 11. 9.
반응형

Python에서 이야기하는 Dictionary 자료 구조는 타 언어에서는 HashMap이라는 명칭으로 사용되나 두개의 명칭 모두 동일한 자료 구조를 가지고 있습니다.

공통적인 특징으로는 key, value의 한쌍의 형태를 띄고 있으며 중복되는 key를 허용하지 않습니다.

Java에서의 HashMap

// HashMap 선언
Map map = new HashMap();
map.put("name", "a");
map.put("age", 100);
map.put("name", "b"); // 처음 대임된 a -> b로 변경 됩니다.

// 결과
// key : name, value : b
// key : age, value : 100
for (Object o : map.keySet()) {
    System.out.println("key : " + o.toString() + ", value : " + map.get(o));
}

map.keySet();                             // key 값들을 Set 형태로 모두 불러옵니다.
map.values();                             // value에 해당하는 값들을 Collection 형태로 불러옵니다.
map.get("name");                          // key에 해당하는 값을 읽기
map.getOrDefault("address", "Not Found"); // key에 해당하는 값이 없을 경우 default 값을 참조
map.containsKey("email");                 // key 값이 map에 포함하는지 확인
map.remove("name1");                      // key에 해당하는 값을 제거
map.clear();                              // 모든 map 내부 데이터 제거

Map map2 = new HashMap();
map.put("name", "aa");
map.put("age", 200);

// 결과
// {name=aa, age=200}
map.putAll(map2);                         // map에 map2의 값을 대입합니다.

Python에서의 Dictionary

dictionary = {"key1": 1, "key2": 2, "key3": 3}

# dictionary 자료구조 내부 조회 함수
print(dictionary.keys()) # dict_keys(['key1', 'key2', 'key3'])
print(dictionary.values()) # dict_values([1, 2, 3])
print(dictionary['key1']) # 1
print(dictionary.get('key5', 'Not Found')) # Not Found

# dictionary 내부 엘리머트 수정 함수
dictionary.update({'key1':5}) # 새로운 dictionary를 참조하여 기존 dictionary에 대입합니다.
dictionary['key1'] = 10 # key1에 해당하는 값을 변경합니다.
dictionary.setdefault('key10',50) # key10이 없는 경우 key10을 default 값과 같이 주입후 default 값을 재 추출합니다.
print(dictionary.pop('key3', 100)) # 3 - key3이 없는 경우 default 값을 출력 합니다.
print(dictionary) # {'key1': 10, 'key2': 2, 'key10': 50}

# dictionary 집합시키기
dictionary = {"key1": 1, "key2": 2, "key3": 3}
dictionary2 = {"key1": 10, "key2": 20, "key3": 30}
dictionary3 = {"key1": 12, "key2": 23, "key3": 34}

# 두개의 dictionary를 병합하여 새로운 dicitionary를 만들거나 대입합니다. 
# | 뒤에오는 dictionary가 우선순위 대상입니다.
dictionary4 = dictionary | dictionary2 
print(dictionary4) # {'key1': 10, 'key2': 20, 'key3': 30}

# 먼저오는 dictionary의 값을 갱신 합니다. | 뒤에오는 dictionary가 우선순위 대상입니다.
# | 뒤에오는 dictionary가 우선순위 대상입니다.
dictionary2 |= dictionary3 
print(dictionary2) # {'key1': 12, 'key2': 23, 'key3': 34}

 

반응형