第13课 字典

Posted nick1998

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第13课 字典相关的知识,希望对你有一定的参考价值。

一、字典

1、字典的定义:{ }   <class ‘dict‘>

>>> dict1 = {}
>>> type(dict1)
<class dict>

2、dict1 = {键1:值,键2:值}

dict2 = {name: Tom, age:18, weight: 130}

3、键值成对出现,不然会报错。

>>> dict2 = {name: Tom, age:18, weight: 130}
>>> dict3 = {name: jacky, age: 18, class}
SyntaxError: invalid syntax

4、通过键来查找元素,没有下标的概念。

>>> dict2 = {name: Tom, age:18, weight: 130}
>>> dict2[weight]
130

1)用len(dict1)来获取字典的长度

>>> dict2 = {name:Tom, age:18 , weight:130}
>>> len(dict2)
3

5、字典里没有同名的key(键),就算有,后面的key也会把前面同名的key覆盖掉。

>>> dict3 = {name:Tom, age:18, name:Jacky}
>>> dict3
{name: Jacky, age: 18}

6、增加元素----格式:dict1[键名] = 值

1)python2--增加字典元素的位置是随机的;

2)python3--从字典后面依次增加

>>> dict3 = {name:Tom, age:18}
>>> dict3[weight] = 136
>>> dict3
{name: Tom, age: 18, weight: 136}

7、如果该字典里面没有这个key,那么打印这个key对应的值会报错----keyerror

>>> dict3 = {name: Tom, age: 18, weight: 136}
>>> print(dict3[class])
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    print(dict3[class])
KeyError: class

8、增加字典的元素:dict1[新键名] = 对应的值

9、字典可以存储任意类型

# 一个键对应的值可以是任意类型
students = {
    Jim Green: {age: 18,   
                  height: 186,
                  weight: 180,
                  nickname: Jimy},
    Linda Smith:{
        age: 23,
        height: 168,
        weight: 108,
        nickname: sweet  }
}

print(students[Linda Smith])


# 执行结果 
{age: 23, height: 168, weight: 108, nickname: sweet}

打印Jim的年龄信息

print(students[Jim Green][age])  # 打印Jim的年龄

#输出结果
18

10、关于key的类型,value的类型

1)key的类型:int、str、float和tuple,但是不能为list(列表)、dict(字典)。hash:散列表----不能改变的类型

注意:对键值操作时不要刻意改变key。

>>> dict1 = {1: int型, 3.14: float型, yy: str型, (6,7,8,9): tuple型}
>>> dict1
{1: int型, 3.14: float型, yy: str型, (6, 7, 8, 9): tuple型}

当key的类型为列表时会报错

>>> dict1 = {[1,2,yy]: list型}
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    dict1 = {[1,2,yy]: list型}
TypeError: unhashable type: list

key的类型为字典也报错

>>> dict1 = {{name: Tom}: 33}
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    dict1 = {{name: Tom}: 33}
TypeError: unhashable type: dict

2)value(值):可以为任意类型

 

二、常用操作

1、判断字典里是否有这个key,可以用---key in dict1;在python2中dict1.has.key(键)的形式。

>>> dict1 = {1: int型, 3.14: float型, yy: str型, (6,7,8,9): tuple型}
>>> 3.14 in dict1
True
>>> xx in dict1
False

2、关于字典的删除元素:字典里面的key相当于list里面的index(下标)

1)del dict1[‘name‘]

>>> dict1 = {name: Tom, age: 21, weight: 130}
>>> del dict1[name]
>>> dict1
{age: 21, weight: 130}

2) value =  dict1.pop(‘name‘)

>>> dict1 = {name: Tom, age: 21, weight: 130}
>>> dict1.pop(name)
Tom
>>> dict1
{age: 21, weight: 130}

3、字典的遍历

1)for one in dict1 ----one依次取key本身的值

>>> dict1 = {name: Tom, age: 21, weight: 130}
>>> for one in dict1:
    print(one)

    
name
age
weight

2)打印字典的值----dict的[one]

>>> dict1 = {name: Tom, age: 21, weight: 130}
>>> for one in dict1:  # one 指的是字典值的内容
    print(dict1[one])

    
Tom
21
130

3)打印字典特定的值-----dict1[one[‘age‘]]

students = {
    Jim Green: {age: 18,
                  height: 186,
                  weight: 180,
                  nickname: Jimy},
    Linda Smith:{
        age: 23,
        height: 168,
        weight: 108,
        nickname: sweet  }
}

for one in students:
    print(students[one][age])

# 执行结果
18
23

4)students.items()----遍历字典的键值对[(键1,  值1),  (键2,  值2)]

print(students.items())

# 结果是一个列表,列表中包含元组
dict_items([(Jim Green, {age: 18, height: 186, weight: 180, nickname: Jimy}), (Linda Smith, {age: 23, height: 168, weight: 108, nickname: sweet})])

把信息从students.items()中取出来---for name, info in students.items():

students = {
    Jim Green: {age: 18,
                  height: 186,
                  weight: 180,
                  nickname: Jimy},
    Linda Smith:{
        age: 23,
        height: 168,
        weight: 108,
        nickname: sweet  }
}


for name, info in students.items():
    print(name, info)

# 执行结果
Jim Green {age: 18, height: 186, weight: 180, nickname: Jimy}
Linda Smith {age: 23, height: 168, weight: 108, nickname: sweet}

4、清空字典内容:

1)dict1.clear()----清空字典本身内容

>>> dict1 = {name: Tom, age: 21, weight: 130}
>>> dict1.clear()
>>> dict1
{}

2)dict1 = {}---把dict1指向一个空字典

>>> dict1 = {name: Tom, age: 21, weight: 130}
>>> dict1 = {}
>>> dict1
{}

5、获取字典中所有的key----dict1.keys(),返回结果在一个列表中

 dict1 = {name: Tom, age: 21, weight: 130}
>>> dict1.keys()
dict_keys([name, age, weight])

6、获取字典中所有的value-----dict1.values(),返回结果在一个列表中

>>> dict1 = {name: Tom, age: 21, weight: 130}
>>> dict1.values()
dict_values([Tom, 21, 130])

7、获取字典中所有的key,value,返回结果在一个列表中

>>> dict1 = {name: Tom, age: 21, weight: 130}
>>> dict1.items()
dict_items([(name, Tom), (age, 21), (weight, 130)])

8、dict1.update----增加字典的元素

>>> dict1 = {name: Tom, age: 21, weight: 130}
>>> dict1.update({1:1, 2:2})
>>> dict1
{name: Tom, age: 21, weight: 130, 1: 1, 2: 2}

练习:2个字典所有的key都一样,请打印具有相同的键值,并打印键值对

dict1 = {1: a, 2: b, 3: c, 4: 100, 5: 200}
dict2 = {1: x, 2: y, 3: z, 4: 100, 5: 200}


for num1 in dict1:
    for num2 in dict2:
        if num1 == num2 and dict1[num1] == dict2[num2]:
            print(num1, dict1[num1])


# 执行结果
4 100
5 200

 

以上是关于第13课 字典的主要内容,如果未能解决你的问题,请参考以下文章

Redis2.6源代码走读第004课:字典的实现02

Redis2.6源代码走读第004课:字典的实现03

Python代码阅读(第19篇):合并多个字典

Python代码阅读(第26篇):将列表映射成字典

Python代码阅读(第40篇):通过两个列表生成字典

python 第35课 字典_复杂表格数据存储_列表和字典综合嵌套