blog/docs/code/python/dict.md

171 lines
3.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: Dictionary 字典
date: 2020-07-24 22:50:55
tags: [Python]
categories: [Python]
author: Anges黎梦
---
## Dictionary 字典
> 字典是另一种可变容器模型,且可存储任意类型对象。
> 字典的每个键值 key=>value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中.
### 键对值key
1. 一个key不允许出现两次key在一个dict中是唯一的。
2. key必须不可变可以用数字字符串元组来定义列表是可变的所以不能作为key
### python版本
python 3.6版本更新的。字典是有序的!!!!
## dict 定义
### {}定义
```
dict_1 = {"name":"anges","age":18}
print(dict_1)
print(type(dict_1))
```
### 空字典定义
```
dict_2 = {} # 定义一个空字典
print(dict_2)
dict_6 = dict() # 创建一个空字典
```
### 以元组为key定义字典
```
dict_3 = {(1,2): 'hello'} # 以元组为key定义字典
print(dict_3)
```
### dict()定义字典
```
dict_4 = dict(a=2,b=7,c=9)
print(dict_4)
```
### 列表定义字典
```
data =[('aaa', 111), ('bbb', 222)] # 元组也可以是列表
dict_5 = dict(data)
print(dict_5)
```
## 字典的基本用法
### 通过key获取对应的value值
```
print(dict_5["aaa"]) # 通过key获取对应的value值
```
### 为字典更新/添加 一个键对值
```
dict_5["ccc"] = 333 # 为字典更新/添加 一个键对值
print(dict_5)
```
### 删除字典中的某一个键对值
```
del dict_5["ccc"] # 删除字典中的某一个键对值
```
### 删除字典
```
del dict_3 # 删除字典
```
### 判断某个key是否存在字典内
```
print("ccc" in dict_5) # 判断某个key是否存在字典内
```
## 内建函数
### len()
返回一共有几个键对值
```
print(len(dict_5)) # 返回一共有几个键对值
```
### clear()
清除字典内所有的元素
```
dict_5.clear() # 清除字典内所有的元素
```
### copy()
字典的复制,浅复制
```
dict_5.copy() # 字典的复制,浅复制
```
### get()
根据一个key获取value值如果没有则返回default中的值
```
dict_5.get("ddd", default=444) # 根据一个key获取value值如果没有则返回default中的值
```
### has_key()
如果key在字典里返回true若不在返回false
```
dict_5.has_key("ccc") # 如果key在字典里返回true若不在返回false
```
### items()
以列表返回可遍历的键对值,元组数组
```
dict_5.items() # 以列表返回可遍历的键对值,元组数组
```
### keys()
以列表返回字典中的所有key
```
dict_5.keys() # 以列表返回字典中的所有key
```
### setdefault()
根据一个key获取value值,如果key不在字典中那么会在字典中添加一个key并且值为default中的值
```
dict_5.setdefault("eee", default=777) # 根据一个key获取value值,如果key不在字典中那么会在字典中添加一个key并且值为default中的值
```
### update()
把字典对象,添加到字典中,两个字典合并
```
dict_5.update() # 把字典对象,添加到字典中,两个字典合并
```
### values()
以列表返回字典中的所有值
```
dict_5.values() # 以列表返回字典中的所有值
```
### pop()
删除字典中给定key的值并返回被删除的值。
```
dict_5.pop() # 删除字典中给定key的值并返回被删除的值。
```
### popitem()
删除并返回字典中最后一对键对值
```
dict_5.popitem() # 删除并返回字典中最后一对键对值
```