[Python3] 016 字典:给我一块硬盘,我可以写尽天下!

目录


0 字典的独白

  1. 英文名:dict()
  2. 我是一种组合数据,没有顺序
  3. 我的数据以“键值对”的形式出现
  4. 键值对:
    1. 听上去有点像高中有机化学里的“化学键”,不过请放心,这里的“键”不会因为吸收能量而“断裂”
    2. 它更像是函数的映射,可以改变指向的值

1 字典的创建

  • 示例:
# 例1.1 创建空字典

d1_1 = {}
d1_2 = dict()

print("d1_1 =", d1_1)
print("d1_2 =", d1_2)
  • 运行结果

d1_1 = {}
d1_2 = {}


# 例1.2 创建有值的字典
# 每一组数据用冒号隔开(冒号相当于“键”)
# 每一对键值对用逗号隔开

d1_3 = {"one":1, "two":2, "three":3}
d1_4 = dict({"one":1, "two":2, "three":3})
d1_5 = dict(one=1, two=2, three=3)
d1_6 = dict( [("one",1), ("two",2), ("three",3)])

print("d1_3 =", d1_3)
print("d1_4 =", d1_4)
print("d1_5 =", d1_5)
print("d1_6 =", d1_6)
  • 运行结果

d1_3 = {'one': 1, 'two': 2, 'three': 3}
d1_4 = {'one': 1, 'two': 2, 'three': 3}
d1_5 = {'one': 1, 'two': 2, 'three': 3}
d1_6 = {'one': 1, 'two': 2, 'three': 3}


2 字典的特性

  1. 字典是序列类型中的无序序列,所以不能分片和索引
  2. 字典中的数据每个都由键值对组成,即 kv 对
    • key:必须是可哈希的值,比如 int,string,float,tuple;但是 list,set,dict 不行
    • value:任何值

3 字典的常见操作

(1) 数据的访问、更改与删除

# 例2.1 访问数据

d2 = {"one":1, "two":2, "three":3}
print(d2["one"])        # 中括号内是键值
  • 运行结果

1


# 例2.2 更改数据;接着例2.1

d2["one"] = "一"
print(d2)
  • 运行结果

{'one': '一', 'two': 2, 'three': 3}


# 例2.3 使用 del 删除一组键值对;接着例2.2

del d2["one"]
print(d2)
  • 运行结果

{'two': 2, 'three': 3}


(2) 成员检测

# 例3 in
# 检测的是 key 的内容

d3 = {"one":1, "two":2, "three":3}

if 2 in d3:
    print("value")
    
if "two" in d3:
    print("key")
    
if ("two",2) in d3:
    print("kv")
  • 运行结果

key

也可以用 not in。


(3) 遍历

# 例4.1 for 循环跟着 key 走

d4 = {"one":1, "two":2, "three":3}

for k in d4:
    print(k, "<-->", d4[k])
  • 运行结果

one <--> 1
two <--> 2
three <--> 3

字典的遍历在 Python2 与 Python3 中区别较大。挖个坑,日后填平,编号 Py016-1。


# 例4.2 例4.1 的代码可以改写成如下样子

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

for v in d4.values():   # 只访问字典的值
    print(v)

for k,v in d4.items():
    print(k,'<-->',v)
  • 运行结果

one 1
two 2
three 3
1
2
3
one <--> 1
two <--> 2
three <--> 3


4 字典生成式

  • 少废话,上例子
# 例5

d5_1 = {"one":1, "two":2, "three":3}

d5_2 = {k:v for k,v in d5_1.items()}    # 常规字典生成式
print(d5_2)

d5_3 = {k:v for k,v in d5_1.items() if v % 2 == 0}  # 加限制条件的字典生成式
print(d5_3)
  • 运行结果

{'one': 1, 'two': 2, 'three': 3}
{'two': 2}


5 字典的内置方法


6 可供字典使用的其它方法/函数

(1) 测量君 len()

# 例6

d6 = {"one":1, "two":2, "three":3}
print(len(d6))
  • 运行结果

3


(2) 最值双子 max() & min()

# 例7.1

d7 = {"one":1, "two":2, "three":3}

print(max(d7))
print(min(d7))
  • 运行结果

two
one

小老弟,你怎么回事?翻车了?

不急,这是错误示范;当然,从 ASCII 码角度讲,t>o; w>h => two 为 max,同理,one 为 min。


# 例7.2

d7 = {"one":1, "two":2, "three":3}

key_max = max(d7, key=d7.get)       # get 见下面补充
key_min = min(d7, key=d7.get)

print(key_max)
print(key_min)
  • 运行结果

three
one


(3) 补充:get(key, default=None)

  • 本想放到内置方法中去的,现在看来,得提前了
  • 释义:如果"键"在字典中,则返回键的值;否则,返回默认值
  • 示例:
# 例8.1

d8 = {"one":1, "two":2, "three":3}

print(d8.get("one"))
print(d8.get("four"))
  • 运行结果

1
None


  • 默认值的默认值为 None,不过可以自定义。
# 例8.2

d8 = {"one":1, "two":2, "three":3}
print(d8.get("four", "sorry"))
  • 运行结果

sorry


  • 注意不要画蛇添足
# 例8.3

d8 = {"one":1, "two":2, "three":3}
print(d8.get("four", default="sorry"))
  • 运行结果

TypeError……get() takes no keyword arguments

get() 不接受关键字参数。


(4) fromkeys(iterable, value=None)

  • 释义:创建一个新字典,由 iterable 中的键 和 value 设置的值构成,value 默认为 None
# 例9
# 使用指定的序列作为键,使用一个值作为字典所有键的值

l9 = ["one", "two", "three"]

d9_1 = dict.fromkeys(l9)
d9_2 = dict.fromkeys(l9, "number")

print(d9_1)
print(d9_2)
  • 运行结果

{'one': None, 'two': None, 'three': None}
{'one': 'number', 'two': 'number', 'three': 'number'}


(5) str(dict)

# 例10

d10 = {"one":1, "two":2, "three":3}
print(str(d10))
  • 运行结果

{'one': 1, 'two': 2, 'three': 3}

猜你喜欢

转载自www.cnblogs.com/yorkyu/p/10293140.html