> For the complete documentation index, see [llms.txt](https://gitbook.existorlive.cn/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gitbook.existorlive.cn/kai-fa-yu-yan-xue-xi/python/9.-zi-dian.md).

# 9.字典

```python
dict = {'name': 'runoob', 'likes': 123, 'url': 'www.runoob.com'}
```

Python中的字典是一种可变的容器，可以用于保存任意类型的对象。\
​

key 必须是不可变类型(如 number，str), value 可以是任意类型\
​

### 字典的操作

```python
# 创建空字典
dic = {} 

dic = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}

# 通过key修改和访问字典
dic['Name'] = 'Runoob1'
print(dic['Age'])

# 删除和清空字典
del dic['Name']        # 删除某个key
dic.remove()           # 清空字典
del dic                # 删除字典




```

**Tip**\
​

key必须是不可变的，因此可以使用 number，str 和 tuple 作为 key，但是 list，dictionary 等可变类型不可以作为key\
​

​

### 字典的函数和方法

```python
len(dic)                      # 字典的长度

str(dic)                      # 将字典转换为字符串

type(dic)                     # 获取类型



dic.clear()                   # 清空

dic.copy()                    # 浅拷贝

dic.fromkeys(iterable,value)     # 根据iterable传进来的值作为 key，以及 默认value 创建新字典


dic.get(key,default = None)   # 获取Key对应的值，key不存在返回默认值
dic[key]                      # 获取Key对应的值，key不存在报错

dic.update(newDic)            # 以newDic来更新 dic

dic.setDefault(key,defaultValue)     # 如果key对应的value不存在，则会设置为defaultValue

dic.items()
dic.keys()
dic.values()

dic.pop(key)
del dic[key]                  # 删除某个key
```

​

​
