Python字典的介绍及实践案例

一、字典(Dict)介绍

字典是Python内置的四大数据结构之一,是一种可变的容器模型,该容器中存放的对象是一系列以(key:value)构成的键值对。其中键值对的key是唯一的,不可重复,且一旦定义不可修改;value可以是任意类型的数据,可以修改。通过给定的key,可以快速的获取到value,并且这种访问速度和字典的键值对的数量无关。字典这种数据结构的设计还与json的设计有异曲同工之妙。(更好的阅读体验,请移步我的个人博客)
       格式如下所示:

d = {key1 : value1, key2 : value2 }

二、使用示例

       2.1. 字典的创建:

d = {'name': 'IT之旅', 'age': 25, 'hobby': ['编程', '看报', 111], 'location': {'天涯', '海角'}, ('male', 'female'): 'male'}print(d)   # {'name': 'IT之旅', 'age': 25, 'hobby': ['编程', '看报', 111], 'location': {'海角', '天涯'}, ('male', 'female'): 'male'}

注意事项:Dict的key必须要是可被hash的,在python中,可被hash的元素有:int、float、str、tuple;不可被hash的元素有:list、set、dict。如下所示:

2.2. 字典的访问:

d = {'name': 'IT之旅', 'age': 25, 'hobby': ['编程', '看报', 111], 'location': {'天涯', '海角'}, ('male', 'female'): 'male'}# 根据键获取值
print(d['name'])  # IT之旅
print(d.get('name'))  # IT之旅# 成员存在则进行访问
if 'age' in d:print(d.get('age'))  # 25# 循环遍历访问
for k in d:print(k, d[k])
'''
name IT之旅
age 25
hobby ['编程', '看报', 111]
location {'天涯', '海角'}
('male', 'female') male
'''
for k, v in d.items():print(k, '-->', v)
'''
name --> IT之旅
age --> 25
hobby --> ['编程', '看报', 111]
location --> {'海角', '天涯'}
('male', 'female') --> male
'''
for v in d.values():print(v)
'''
IT之旅
25
['编程', '看报', 111]
{'海角', '天涯'}
male
'''

2.2. 修改字典的值:

d = {'name': 'IT之旅', 'age': 25, 'hobby': ['编程', '看报', 111], 'location': {'天涯', '海角'}, ('male', 'female'): 'male'}print(d['age'])  # 25d['age'] = 27
print(d['age'])  # 27

2.3. 删除字典的元素:

d = {'name': 'IT之旅', 'age': 25, 'hobby': ['编程', '看报', 111], 'location': {'天涯', '海角'}, ('male', 'female'): 'male'}del d['name']
print(d)  # name键值对已被删除d.clear()
print(d)  # d已被清除,输出为空的对象 {}
del d
print(d)  # name 'd' is not defined

2.4. 增加字典元素:

d = {'name': 'IT之旅', 'age': 25, 'hobby': ['编程', '看报', 111], 'location': {'天涯', '海角'}, ('male', 'female'): 'male'}del d['name']
del d['hobby']
del d['location']
print(d)  # {'age': 25, ('male', 'female'): 'male'}d.update({'name_1': '测试用户名'})  # 添加元素值
print(d)  # {'age': 25, ('male', 'female'): 'male', 'name_1': '测试用户名'}m = {'test': 'test', 1: 1}  # 合并字典值
d.update(m)
print(d)  # {'age': 25, ('male', 'female'): 'male', 'name_1': '测试用户名', 'test': 'test', 1: 1}

2.5. 字典的复制:

d = {'name': 'IT之旅', 'age': 25, 'hobby': ['编程', '看报', 111], 'location': {'天涯', '海角'}, ('male', 'female'): 'male'}m = d.copy()  # 浅复制
print(m == d)  # True
print(id(m) == id(d))  # Falsen = d  # 直接赋值
print(id(n) == id(d))  # True'''
需要注意直接赋值和浅拷贝的区别
'''

2.6.  python内置了一些函数用于操作字典,包含有:计算字典元素个数的len()函数,以可打印字符串输出的str()函数,删除字典给定键 key 所对应值的pop()函数,等等。

三、实践案例 - 统计英文文章中单词出现的频率

英文句子如下:

With the gradual deepening of Internet of things, artificial intelligence, big data and other concepts, the construction of smart city is particularly urgent, and smart transportation is an important step in this link, which is not only the key words of urban construction,
It is also an important traffic information data of each city component. In order to strengthen data information sharing and exchange, each region has begun to make efforts to build.
As an important indicator of road section, traffic indicator cone plays an important role in road section status indication and vehicle drainage.
The traditional cone barrel has some disadvantages, such as single function, poor warning effect, inconvenient transportation and poor ability to withstand harsh conditions, which can not meet the requirements of current conditions. Based on this situation,
We start to use NB-IoT communication technology and IPv6 protocol to further explore the use value of cone barrel and further improve the utilization rate.
What is the next direction of the Internet of things? We'll see

代码如下:(将上面的单词放进一个文本中,然后修改代码中文本文件的位置即可运行代码)

original_words = open(r'C:\Users\itour\Desktop\words-original.txt', 'r', encoding='utf-8')
# 将文本中的句子分割成一个一个单次,去除标点符号后存入word_list列表中。
word_list = []
for lines in original_words:word = lines.replace('\n', '').split(' ')for reduce_word in word:  # 去除单次中的标点符号word_list.append(reduce_word.strip(',').strip('?').strip('.'))# 使用字典数据结构统计单词出现的频率
word_dict = {}
for w in word_list:if w in word_dict.keys():word_dict[w] += 1else:word_dict[w] = 1
# 输出结果
print(word_dict)'''
{'With': 1, 'the': 8, 'gradual': 1, 'deepening': 1, 'of': 10, 'Internet': 2,
'things': 2, 'artificial': 1, 'intelligence': 1, 'big': 1, 'data': 3, 'and': 7,'other': 1, 'concepts': 1, 'construction': 2, 'smart': 2, 'city': 2, 'is': 5, 'particularly': 1, 'urgent': 1, 'transportation': 2, 'an': 4, 'important': 4, 'step': 1, 'in': 2, 'this': 2, 'link': 1, 'which': 2, 'not': 2, 'only': 1, 'key': 1, 'words': 1, 'urban': 1, 'It': 1, 'also': 1, 'traffic': 2, 'information': 2, 'each': 2, 'component': 1, 'In': 1, 'order': 1, 'to': 6, 'strengthen': 1, 'sharing': 1, 'exchange': 1,'region': 1, 'has': 2, 'begun': 1, 'make': 1, 'efforts': 1, 'build': 1, 'As': 1, 'indicator': 2, 'road': 2, 'section': 2, 'cone': 3, 'plays': 1, 'role': 1, 'status': 1, 'indication': 1, 'explore': 1}'''

四、总结

Python的字典数据结构,在很多方面都有应用,因此,掌握这个数据结构是非常必要的。

Python内置四大数据结构之字典的介绍及实践案例相关推荐

  1. python内置的数据结构_Python内置数据结构

    「Python数据分析养成记」 第四篇 前言 前文讲解了Python的基础数据类型,但是对于复杂的问题,最基础的数据类型可能没法解决.例如,每个变量(容器)只能装一种饮料(雪碧或者可乐),那能否一个变 ...

  2. python内置容器--元组,字典与集合

    1.4.原组 1.4.1.元组(tuple):将一组不可变的数据序列组合起来形成一个特殊的内置容器 1.4.2元组不允许的操作: 修改,新增元素 删除元素(允许删除整个元组) 所有会对元组内部元素发生 ...

  3. python内置的数据结构_python内置的数据结构

    详解列表List 这里是列表对象方法的清单: list.append(x) 添加一个元素到列表的末尾.相当于a[len(a):] = [x]. list.extend(L) 将给定列表L中的所有元素附 ...

  4. python / 内置的数据结构概述

    @time 2019-07-30 @author Ruo_Xiao @notice 后续部分这两天补充. 零.前言 type 中文名称 list 列表 tuple 元组 dict 字典 set 集合 ...

  5. python内置函数可以返回列表元组_Python内置函数()可以返回列表、元组、字典、集合、字符串以及range对象中元素个数....

    Python内置函数()可以返回列表.元组.字典.集合.字符串以及range对象中元素个数. 青岛远洋运输有限公司冷聚吉船长被评为全国十佳海员.()A:错B:对 有源逆变是将直流电逆变成其它频率的交流 ...

  6. python内置函数用来返回列表、元组、字典_python程序设计第一章基础知识 题库及选解...

    由于学校的python是笔试,所以找了份感觉比较好的题库刷了下其中前八章的填空和判断,附上选解.各章链接如下 填空 1. Python安装扩展库常用的是()工具.(pip) 2. Python标准库m ...

  7. Python基础(四)(列表、元组、字典、字符串、Python内置函数、切片、运算符、成员运算符)

    高级变量类型 知识点回顾 Python 中数据类型可以分为 数字型 和 非数字型 数字型 整型 (int) 浮点型(float) 布尔型(bool) 真 True 非 0 数 -- 非零即真 假 Fa ...

  8. python内置函数什么可以返回列表、元组_Python内置函数_________可以返回列表、元组、字典、集合、字符串以及range对象中元素个数。...

    [单选题]如果希望把一个可迭代对象转换为元组,该使用下面的哪个函数? [单选题]已知 x = [1, 2],那么执行语句 x[0:0] = [3, 3]之后,x的值为___________. [单选题 ...

  9. python 内置函数

    python 内置函数 Python内置(built-in)函数随着python解释器的运行而创建.在Python的程序中,你 可以随时调用这些函数,不需要定义. abs()     # 求一个数的绝 ...

最新文章

  1. Python+OpenCV 图像处理系列(9)—— 图像的翻转和缩放插值
  2. 实探全球第九大超算中心:温水冷却节能30% 正寻求新突破
  3. java并发编程线程安全
  4. [视频教程] docker端口映射与目录共享运行PHP
  5. 【Codeforces - 找不到题号】三元环计数(bitset优化,压位)
  6. 海龟交易法则07_如何衡量风险
  7. SAS安装后处理错误的解决方法
  8. 计算机主机hdmi接口是什么意思,hdmi接口有什么用,教你详细的计算机hdmi接口功能...
  9. [含lw+源码等]S2SH+mysql的报刊订阅系统[包运行成功]Java毕业设计计算机毕设
  10. 『市场基础变量计算』
  11. IOS 编程初体验 第一篇:自学和培训的选择
  12. 机器阅读理解 | (1) 智能问答概述
  13. 阿里云盘内测邀请码是多少?阿里云盘邀请码获得方法
  14. 国内有哪些好的刷题网站?
  15. Cheat Engine 在mac最新系统无法安装的解决办法
  16. tdm的应用计算机,2021计算机考研备考知识:TDM时分复用技术
  17. java常用混淆工具(有链接)
  18. m被3整除的c语言表达式,C语言编写函数fun,实现从整数m到n,能被3整除
  19. 立可得_第2章_新零售_重构人、货、场
  20. Kylin(二)安装使用

热门文章

  1. Leetcode 214.最短回文串
  2. 森林结点数,边数与树个数的关系
  3. 自治系统中单个路由表的构造
  4. oracle创建用户和角色、管理授权以及表空间操作
  5. 日常开发中的几个常用跨域处理方式
  6. React Native 首次加载白屏优化
  7. 2014ACM/ICPC亚洲区西安站 F题 color (组合数学,容斥原理)
  8. BestCoder Round #14 B 称号 Harry And Dig Machine 【TSP】
  9. JXL读取,写入Excel
  10. iPhone NavigationBar和UIToolbar基础