字典(dictionary)是一系列键值对。每个相关联的可以是数、字符串、列表、元组乃至字典。

Code
alien_0 = {"color":"green","points":5}
alien_0
{'color': 'green', 'points': 5}

4.1 操纵字典

4.1.1 访问值

Code
alien_0["color"]
alien_0["points"]
5

4.1.2 添加键值对

Code
alien_0["x"] = 0
alien_0["y"] = 25
alien_0
{'color': 'green', 'points': 5, 'x': 0, 'y': 25}

4.1.3 从空字典开始

Code
alien_0 = {}
alien_0["color"]  = "green"
alien_0["points"] = 5

alien_0
{'color': 'green', 'points': 5}

4.1.4 修改

Code
alien_0["color"] =[ "yellow","red","blue"]
alien_0
{'color': ['yellow', 'red', 'blue'], 'points': 5}

4.1.5 删除

Code
alien_0 = {"color":"green","points":5}

del alien_0["points"]
alien_0
{'color': 'green'}

4.1.6 由类似的对象组成的字典

Code
like_language={
    "jen":"python",
    "sarah":"c",
    "edward":"r",
    "phil":"python",
    }
like_language
{'jen': 'python', 'sarah': 'c', 'edward': 'r', 'phil': 'python'}

4.1.7 get()方法访问值

Code
alien_0["speed"]
#>>> Traceback (most recent call last):
#>>>   File "<string>", line 1, in <module>
#>>> KeyError: 'speed'

get()方法第一个参数用于指定键key,第二个参数为指定的键不存在时的返回值。

Code
alien_0 = {"color":"green","points":5}
alien_0.get("color")
alien_0.get("speed","Error,no existing")
'Error,no existing'

4.2 遍历字典

4.2.1 遍历所有键值对

Dict.items()

Code
like_language={
    "jen":"python",
    "sarah":"c",
    "edward":"r",
    "phil":"python",
    }
like_language.items()

for i,j in like_language.items():
    print(f"Key:{i}")
    print(f"Value:{j}")
    print(f"{i.title()}'s favorite language is {j.title()}.\n")
Key:jen
Value:python
Jen's favorite language is Python.

Key:sarah
Value:c
Sarah's favorite language is C.

Key:edward
Value:r
Edward's favorite language is R.

Key:phil
Value:python
Phil's favorite language is Python.

4.2.2 遍历所有键

Dict.keys()

Code
like_language.keys()

for i in like_language.keys():
    print(f"Key:{i.title()}")
Key:Jen
Key:Sarah
Key:Edward
Key:Phil
Note

默认遍历使用键

Code
for i in like_language: 
    print(f"Key:{i.title()}")
Key:Jen
Key:Sarah
Key:Edward
Key:Phil

4.2.3

4.3 默认遍历键

for i in like_language: print(f”Key:{i.title()}“)

4.3.1 按特定顺序遍历所有键

sorted()函数

Code
like_language={
    "jen":"python",
    "sarah":"c",
    "edward":"r",
    "phil":"python",
    }
for i in sorted(like_language.keys()):
    print(i.title())
Edward
Jen
Phil
Sarah

4.3.2 遍历所有值

Dict.values()

Code
like_language.values()
for lan in like_language.values():
    lan.title()

为剔除重复项,可使用集合set()函数。

Code
for lan in set(like_language.values()):
    lan.title()

4.4 集合set

Note

集合的性质:互异性,无序性,确定性。

可以使用一对花括号{}直接创建集合,用逗号分隔。

Code
language_set = {"python","r","c"}
language_set
{'c', 'python', 'r'}

4.5 嵌套

4.5.1 字典列表

列表的每个元素是一个字典

Code
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10} 
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2] 
for alien in aliens: 
    print(alien)
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}

4.5.2 在字典中存储列表

Code
r_object = {
    "num":[1,2,3,4,5],
    "strings":["qwe","asd","zxc"],
    "bool":[True,False],
}
r_object["num"]
[1, 2, 3, 4, 5]

4.5.3 在字典中存储字典

Code
email = {
    "Tencent":{
        "prefix":"3036683293",
        "suffix":"@qq.com",
        "state":"hardly"
    },
    "USTC":{
        "prefix":"wangal00",
        "suffix":"@mail.ustc.edu.cn",
        "state":"usually",
    },
    "Microsoft":{
        "prefix":"wanganlin00",
        "suffix":"@outlook.com",
        "state":"often",
    },
    "Google":{
        "prefix":"wanganlin00",
        "suffix":"@gmail.com",
        "state":"can't",
    },
}
for i,j in email.items():
    print(f"Belongs to {i}:")
    print(f'My email is {j["prefix"]}{j["suffix"]} , I {j["state"]} use it.\n')
Belongs to Tencent:
My email is 3036683293@qq.com , I hardly use it.

Belongs to USTC:
My email is wangal00@mail.ustc.edu.cn , I usually use it.

Belongs to Microsoft:
My email is wanganlin00@outlook.com , I often use it.

Belongs to Google:
My email is wanganlin00@gmail.com , I can't use it.