---
title: "datatype-dictionary (tc)"
description: "字典（dictionary）：key:value 儲存——取值、.items() 逐個讀、value 是 list、keys 變 list、_ 做 key。"
url: "https://aaronchan.com/zh/kb/datatype-dictionary/"
updated: "2026-09-15"
category: "Code-Python (tc)"
tags:
  - python
---

# datatype-dictionary (tc)

字典（dictionary）用一對對的 key:value 儲存資料，要取得 value 就用 key 去查。以下 5 個例子：基本取值、逐個讀（`.items()`）、value 是 list、把 keys 變成 list（`list(dict.keys())`）、用 `_` 做 key 變數名。

## Example 1：建立字典 + 用 key 取值

 Copy

```
dict1={"key1":"john", "key2":"paul"}
print (dict1["key1"])
```

**output:**

```
john
```

---

## Example 2：逐個讀 key 和 value（.items()）

 Copy

```
my_dict = {'apple': 3, 'banana': 5, 'orange': 2}

for key, value in my_dict.items():
    print(f'{key} : {value}')
```

**output:**

```
apple : 3
banana : 5
orange : 2
```

---

## Example 3：value 是 list

 Copy

```
dictStu = {'StuName': ['Ada, Billy, Cindy'], 'ChiScore': [10,20,30]}
for key in dictStu:
    print(f'{key}: {dictStu[key]}')
```

**output:**

```
StuName: ['Ada, Billy, Cindy']
ChiScore: [10, 20, 30]
```

---

## Example 4：把 keys 變成 list（list(dict.keys())）

 Copy

```
dictStu = {'StuName': 'Ada',
           'ChiScore': 'A'}
keys = list(dictStu.keys())
print(keys)

count=0
while (count<len(keys)):
    print (f'{keys[count]}:{dictStu[keys[count]]}')
    count=count+1
```

**output:**

```
['StuName', 'ChiScore']
StuName:Ada
ChiScore:A
```

---

## Example 5：用 _ 做 key 變數名

 Copy

```
dict1 = {'aaa':111, 'bbb':222, 'ccc':333}
for _, value in dict1.items():
    print (f'key={_}, value={value}')
```

**output:**

```
key=aaa, value=111
key=bbb, value=222
key=ccc, value=333
```
