一、字典(Dict)介绍
字典是Python内置的四大数据结构之一,是一种可变的容器模型,该容器中存放的对象是一系列以(key:value)构成的键值对。其中键值对的key是唯一的,不可重复,且一旦定义不可修改;value可以是任意类型的数据,可以修改。通过给定的key,可以快速的获取到value,并且这种访问速度和字典的键值对的数量无关。字典这种数据结构的设计还与json的设计有异曲同工之妙。
格式如下所示:
d = {key1 : value1, key2 : value2 }
二、使用示例
2.1. 字典的创建:
1 | 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. 字典的访问:
1 | d = {'name': 'IT之旅', 'age': 25, 'hobby': ['编程', '看报', 111], 'location': {'天涯', '海角'}, ('male', 'female'): 'male'} |
2.2. 修改字典的值:
1 | d = {'name': 'IT之旅', 'age': 25, 'hobby': ['编程', '看报', 111], 'location': {'天涯', '海角'}, ('male', 'female'): 'male'} |
2.3. 删除字典的元素:
1 | d = {'name': 'IT之旅', 'age': 25, 'hobby': ['编程', '看报', 111], 'location': {'天涯', '海角'}, ('male', 'female'): 'male'} |
2.4. 增加字典元素:
1 | d = {'name': 'IT之旅', 'age': 25, 'hobby': ['编程', '看报', 111], 'location': {'天涯', '海角'}, ('male', 'female'): 'male'} |
2.5. 字典的复制:
1 | d = {'name': 'IT之旅', 'age': 25, 'hobby': ['编程', '看报', 111], 'location': {'天涯', '海角'}, ('male', 'female'): 'male'} |
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
代码如下:(将上面的单词放进一个文本中,然后修改代码中文本文件的位置即可运行代码)
1 | original_words = open(r'C:\Users\itour\Desktop\words-original.txt', 'r', encoding='utf-8') |
四、总结
Python的字典数据结构,在很多方面都有应用,因此,掌握这个数据结构是非常必要的。