# Go 语言基础入门教程 —— 数据类型篇：字典类型的遍历和排序

### 遍历字典

```testMap := map[string]int{
"one": 1,
"two": 2,
"three": 3,
}

for key, value := range testMap {
fmt.Println(key, value)
}```

```three 3
one 1
two 2```

```for _, value := range testMap {
fmt.Println(value)
}```

```for key := range testMap {
fmt.Println(key)
}```

### 键值对调

```invMap := make(map[int] string, 3)

for k, v := range testMap {
invMap[v] = k
}

for k, v := range invMap {
fmt.Println(k, v)
}```

```3 three
1 one
2 two```

### 字典排序

```keys := make([]string, 0)
for k, _ := range testMap {
keys = append(keys, k)
}

sort.Strings(keys)  // 对键进行排序

fmt.Println("Sorted map by key:")
for _, k := range keys {
fmt.Println(k, testMap[k])
}```

```Sorted map by key:
one 1
three 3
two 2```

```values := make([]int, 0)
for _, v := range testMap {
values = append(values, v)
}

sort.Ints(values)   // 对值进行排序

fmt.Println("Sorted map by value:")
for _, v := range values  {
fmt.Println(invMap[v], v)
}```

```Sorted map by value:
one 1
two 2
three 3```

67 篇文章12 人订阅

0 条评论