Python3笔记019 - 4.4 字典

第4章 序列的应用

  • 4.1 序列
  • 4.2 列表
  • 4.3 元组
  • 4.4 字典
  • 4.5 集合
  • 4.6 列表、元组、字典、集合的区别

python的数据类型分为:空类型、布尔类型、数字类型、字节类型、字符串类型、元组类型、列表类型、字典类型、集合类型

在python中序列是一块用于存放多个值的连续内存空间。

python内置了5种序列分别是元组、列表、字典、集合、字符串

本章将介绍元组、列表、字典、集合四种序列类型,字符串将在第5章介绍

4.4 字典

字典的特征:

1、通过键而不是通过索引来读取

2、字典是可变的,并且可以任务嵌套

3、字典中的键必须唯一

4、字典中的键必须不可变

5、从3.6版本开始,是有序序列

4.4.1 字典的创建和删除

1、直接使用{}创建字典

dictonary = {"key1":"value1", "key2":"value2", ..., "keyn":"valuen"}
参数说明
dictionary表示字典名称
key1、key2、...keyn表示元素的键,必须唯一
value1、value2、...、valuen表示元素的值,不须唯一
dict1 = {"Monday":"星期一","Tuesday":"星期二","wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六","Sunday":"星期日",}
print(type(dict1))
output:
<class 'dict'>
dictionary = {} # 空字典
dictionary = dict() # 空字典

2、通过映射函数创建字典

dictionary = dict(zip(list1, list2))
参数说明
dictionary表示字典名称
zip()函数用于将多个列表或元组对应位置的元素组合为元组,并返回包含这些内容的zip对象
list1 = ["星期一","星期二","星期三","星期四","星期五","星期六","星期日"]
list2 = ["Monday","Tuesday","wednesday","Thursday","Friday","Saturday","Sunday"]
dictionary = dict(zip(list1, list2))
print(type(dictionary))
print(dictionary)
output:
<class 'dict'>
{'星期一': 'Monday', '星期二': 'Tuesday', '星期三': 'wednesday', '星期四': 'Thursday', '星期五': 'Friday', '星期六': 'Saturday', '星期日': 'Sunday'}

3、通过给定的关键字参数创建字典

dictionary = dict(key1=value1, key2=value2, ..., keyn=valuen)
dictionary = dict(key1="value1", key2="value2", keyn="valuen")
print(type(dictionary))
print(dictionary)
output:
<class 'dict'>
{'key1': 'value1', 'key2': 'value2', 'keyn': 'valuen'}

4、删除字典

del dictionary
dictionary.clear()
dictionary = dict(key1="value1", key2="value2", keyn="valuen")
del dictionary
print(dictionary)
output:
NameError: name 'dictionary' is not defined
dictionary = dict(key1="value1", key2="value2", keyn="valuen")
dictionary.clear()
print(dictionary)
output:
{}

4.4.2 通过键值对访问字典

1、通过键访问值

ditionary[key]
dict1 = {"Monday":"星期一","Tuesday":"星期二","wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六","Sunday":"星期日",}
print(dict1["Monday"])
output:
星期一

2、通过字典对象的get()方法

dictionary.get(key[,default])
dict1 = {"Monday":"星期一","Tuesday":"星期二","wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六","Sunday":"星期日",}
print(dict1.get("Monday"))
output:
星期一

4.4.3 遍历字典

1、keys()

dict1 = {"Monday":"星期一","Tuesday":"星期二","wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六","Sunday":"星期日",}
for i in dict1.keys():
    print(i)
output:
Monday
Tuesday
wednesday
Thursday
Friday
Saturday
Sunday

2、values()

dict1 = {"Monday":"星期一","Tuesday":"星期二","wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六","Sunday":"星期日",}
for i in dict1.values():
    print(i)
output:
星期一
星期二
星期三
星期四
星期五
星期六
星期日

3、items()

dict1 = {"Monday":"星期一","Tuesday":"星期二","wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六","Sunday":"星期日",}
for i in dict1.items():
    print(i)
output:
('Monday', '星期一')
('Tuesday', '星期二')
('wednesday', '星期三')
('Thursday', '星期四')
('Friday', '星期五')
('Saturday', '星期六')
('Sunday', '星期日')

4.4.4 添加、修改、删除字典元素

dict1 = {"Monday":"星期一","Tuesday":"星期二","wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六",}
# 添加
dict1["Sunday"]="星期日"
print(dict1)
output:
{'Monday': '星期一', 'Tuesday': '星期二', 'wednesday': '星期三', 'Thursday': '星期四', 'Friday': '星期五', 'Saturday': '星期六', 'Sunday': '星期日'}
# 修改
dict1 = {"Monday":"星期一","Tuesday":"星期二","wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六","Sunday":"星期日",}
dict1["Sunday"]="星期天"
print(dict1)
output:
{'Monday': '星期一', 'Tuesday': '星期二', 'wednesday': '星期三', 'Thursday': '星期四', 'Friday': '星期五', 'Saturday': '星期六', 'Sunday': '星期天'}
# 删除
dict1 = {"Monday":"星期一","Tuesday":"星期二","wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六","Sunday":"星期日",}
del dict1["Sunday"]
# 如果要删除的元素不存在,会抛出异常,可以先做个判断
dict1 = {"Monday":"星期一","Tuesday":"星期二","wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六","Sunday":"星期日",}
if "Sunday" in dict1:
    del dict1["Sunday"]
print(dict1)
output:
{'Monday': '星期一', 'Tuesday': '星期二', 'wednesday': '星期三', 'Thursday': '星期四', 'Friday': '星期五', 'Saturday': '星期六'}

4.4.5 字典推导式

import random
randomdict = {i:random.randint(10,100) for i in range(1,5)}
print("生成的字典为:",randomdict)
output:
生成的字典为: {1: 41, 2: 40, 3: 45, 4: 10}
# 拓展:值最大的字典
def max_pairs(dic):
    if len(dic) == 0:
        return dic
    max_val = max(map(lambda v: v[1], dic.items()))
    return [item for item in dic.items() if item[1] == max_val]


r = max_pairs({'a': -10, 'b': 5, 'c': 3, 'd': 5})
print(r)  # [('b', 5), ('d', 5)]
# 拓展:合并两个字典
def merge_dict2(dic1, dic2):
    return {**dic1, **dic2}  # python3.5后支持一行代码实现合并字典

merge_dict({'a': 1, 'b': 2}, {'c': 3})  # {'a': 1, 'b': 2, 'c': 3}

敬请关注个人微信公众号:测试工匠麻辣烫

posted @ 2020-07-03 08:15  测试工匠麻辣烫  阅读(181)  评论(0编辑  收藏  举报