Skip to content

dict(字典)

定义:字典是一种可变的、无序的、键值对的、复杂的数据容器

Python 中的字典是一个键值映射的数据结构。

字典是一种可变无序数据容器,且可存储任意类型对象。 字典的每个键值 key=>value 对用冒号 : 分割, 每个键值对之间用逗号 , 分割,整个字典包括在花括号 {}

字典的定义

字典用 {} 定义,使用键值对存储数据,键值对之间使用 , 分隔

  • key 是索引
  • value 是数据
  • 键和值之间使用 : 分隔
  • 键必须是唯一的
  • 值可以取任何数据类型,但键只能使用字符串、数字或元组
python
dict1 = {
    "name": "小明",
    "age": 18,
    "gender": True,
    "height": 1.65
}

复杂字典的定义

python
>>> dict2 = {
...     'name': '正心',
...     'age': 18,
...     'gender': True,
...     'height': 1.65,
...     'info': {
...         'address': '中国.湖南.长沙',
...         'hobby': ['吃饭', '睡觉', '写代码']
...     }
... }
>>> print(dict2)
{'name': '正心', 'age': 18, 'gender': True, 'height': 1.65, 'info': {'address': '中国.湖南.长沙', 'hobby': ['吃饭', '睡觉', '写代码']}}
>>> import pprint 
>>> pprint.pprint(dict2)  # pprint 格式化打印
{'age': 18,
 'gender': True,
 'height': 1.65,
 'info': {'address': '中国.湖南.长沙', 'hobby': ['吃饭', '睡觉', '写代码']},
 'name': '正心'}

字典常用操作

使用 字典['键'] 可以取到字典里面的内容。

python
>>> dict1 = {
...     "name": "小明",
...     "age": 18,
...     "gender": True,
...     "height": 1.65
... }
>>> print(dict1['name'])
小明

使用 字典['键'] = 值 修改字典内容。

python
>>> dict1['height'] = 0
>>> print(dict1)           
{'name': '小明', 'age': 18, 'gender': True, 'height': 0}

当键不存在时添加内容。

python
>>> dict1['weight'] = '60kg'
>>> print(dict1) 
{'name': '小明', 'age': 18, 'gender': True, 'height': 0, 'weight': '60kg'}

字典取值

普通字典取值

python
dict1 = {
    'name': '正心',
    'age': 18,
    'gender': '男',
    'height': 1.65
}

print('姓名:', dict1['name'])
print('身高:', dict1.get('weight'))  # .get 没有值就返回默认的 None, 不会报错
print('身高:', dict1.get('weight', None))
print('身高:', dict1.get('weight', '注册用户的时候没有预留身高'))

嵌套字典取值

python
import pprint

dict2 = {
    'name': '正心',
    'age': 18,
    'gender': True,
    'height': 1.65,
    'info': {
        'address': '中国.湖南.长沙',
        'hobby': ['吃饭', '睡觉', '写代码']
    }
}

print(dict2)
print('姓名: ', dict2['name'])  # 字典是根据键取值
print('爱好: ', dict2['info']['hobby'])

# 给字典的键赋值,如果键存在就会覆盖
dict2['gender'] = '男'

# 给字典的键赋值,如果键不存在,就会新增一个键值对
dict2['skill'] = ['python', 'javascript']
pprint.pprint(dict2)

案例-字典取值

python
"""
要求:从字典中提取歌手、歌名、音乐地址
"""
data = {
    "state": True,
    "errno": 22000,
    "errmsg": "",
    "elapsed_time": "0.0122",
    "data": {
        "artist": [
            {
                "artistCode": "A10047720",
                "birthday": "1983-07-17",
                "gender": "男",
                "name": "薛之谦",
                "artistType": 38,
                "artistTypeName": "歌手",
                "pic": "https://img01.dmhmusic.com/0101/M00/F8/AE/ChR45V7XEJWAZJ8KAAL8wj6aS4w115.jpg",
                "region": "",
            }
        ],
        "cpId": 23,
        "pic": "https://img01.dmhmusic.com/0412/M00/FE/96/ChAKEl_IzFiAUZyEAA-Q7DRXeIo850.jpg",
        "title": "你还要我怎样",
        "duration": 310,
        "assetId": "T10038986648",
        "genre": "流行",
        "albumTitle": "意外",
        "id": "T10038986648",
        "lang": "中文",
        "afReplayGain": -0.370003,
        "albumAssetCode": "P10001640807",
        "releaseDate": "2013-11-11T00:00:00.000Z",
        "isrc": "CNA651302299",
        "sort": 3,
        "meanVolume": -17.1,
        "maxVolume": 0,
        "lyric": "https://static-qianqian.taihe.com/0412/M00/FE/96/ChAKEl_IzFiAA1agAAAG_sbemkw066.lrc",
        "pay_model": 2,
        "TSID": "T10038986648",
        "allRate": ["320", "128", "3000", "64"],
        "pushTime": "2019-03-05T16:42:51+08:00",
        "downTime": "2037-01-01T00:00:00+08:00",
        "bizList": ["sdk_cpm"],
        "bits": 16,
        "path": "https://audio04.dmhmusic.com/71_53_T10038986648_128_4_1_0_sdk-cpm/cn/0208/M00/E5/61/ChR46119DrGAW4d4AEvErRDwLyg867.mp3?xcode=c1a597cce27ff185785e95c6cf346f934713ee4",
        "size": 4965549,
        "rate": 128,
        "hashcode": "cee20c55e4518f0511c101f76c2914c0ba9895b9",
        "format": "mp3",
        "filemd5": "feacadc129c14b6418d7bd12864b1757",
        "expireTime": 1609416230,
        "isFavorite": 0,
        "isVip": 0,
    },
}

print(data)
"""

要求以以下格式输出:

歌手: 薛之谦
歌名: 你还要我怎样
音乐地址: https://audio04.dmhmusic.com/71_53_T10038986648_128_4_1_0_sdk-cpm/cn/0208/M00/E5/61/ChR46119DrGAW4d4AEvErRDwLyg867.mp3?xcode=c1a597cce27ff185785e95c6cf346f934713ee4
"""

最后点击一下音乐地址,你会发现一件神奇的事情 φ(>ω<*)

python
print('歌手: ', data["data"]["artist"][0]['name'])
print('歌名: ', data["data"]["title"])
print('音乐地址: ', data["data"]["path"])

字典常用方法

clear       items       setdefault
copy        keys        update
fromkeys    pop         values
get         popitem

有关字典的常用操作 可以参照上图练习

方法用法
get(key, default=None)返回指定键的值,如果值不在字典中返回 default
keys()以列表返回一个字典所有的键
values()以列表返回字典中的所有值
update(dict2)把字典 dict2 的键/值对更新到dict里
items()以列表返回可遍历的(键, 值) 元组数组

循环遍历

遍历 就是 依次 从 字典 中获取所有键值对

python
# for 循环内部使用的 `key 的变量` in 字典

for k, v in dict1.items():
    print(k, v)

for k in dict1.keys():
    print(k, dict1[k])

提示:在实际开发中,由于字典中每一个键值对保存数据的类型是不同的,所以针对字典的循环遍历需求并不是很多

案例:字符统计

统计 python 之禅中每个字符出现的次数

python
from this import s

d = {}
for i in s:
    if i not in d.keys():
        d[i] = 1
    else:
        d[i] += 1

for k, v in d.items():
    print(f"字符 {k} 出现了 {v} 次")

拓展:对字典进行排序输出

python
# 1. 字典是无序的,需要改变结构
l = list(d.items())


def func(temp):
    return temp[1]


# 2. 需要指定列表里面的元素的第二个值进行排序
l.sort(key=func, reverse=True)

print(l)
for i in l:
    print(f"字符 {i[0]} 出现了 {i[1]} 次")