# [python study note] 사전

### 1\. **사전**

key-value pair. 키와 값이 쌍을 이룬다.

```plaintext
dictionary = {
    5:25,
    2:4,
    3:9
}

#값을 가져오려면 대괄호 안에 키를 넣어주면 된다.
print(dictionary[5]) #25
```

**사전에 새로운 쌍 추가하기**

```plaintext
dictionary[9] = 18
print(dictionary) #{5: 25, 2: 4, 3: 9, 9: 18}
```

---

### 2\. 사전과 리스트의 차이점

사전과 리스트는 비슷해 보이지만

리스트는 인덱스가 순서대로 0, 1, 2, 3, 4로 진행되고, 사전은 순서의 개념이 없다.

또한 리스트의 인덱스는 무조건 정수값이지만, 사전의 키는 정수형일 필요가 없다.

---

### 3\. 사전 활용

**사전에 어떤 값이 있는지 목록 확인**

```plaintext
사전이름.values()
```

**ex)**

```plaintext
dict = {
    5:25,
    2:4,
    3:9
}
print(dict.values()) #dict_values([25, 4, 9])
print(25 in dict.values()) #True

#값 하나씩 불러오기
for value in dict.values():
    print(value)
```

**사전에서 키 불러오기**

```plaintext
print(dict.keys()) #dict_keys([5, 2, 3])
```

**키와 값 불러오기**

```plaintext
for key, value in dict.items():
    print(key, value)
#5 25
#2 4
#3 9
```
