Dictionary type of Python combined data type

Unit overview
Mainly solve the problem: let the program handle a set of data better
Three types of important combination data types: collection type, sequence type and dictionary type

After studying this chapter, we can build patterns of sets, sequences and dictionaries in our minds to express and process a set of data

1. Definition

First understand the concept of "mapping"
-mapping is a key (index) and value (data) correspondence

The sequence type is 0...N integer as the default index of the data, and the
mapping type is defined by the user for the data index

A dictionary is a collection of key-value pairs, with no order between key-value pairs

Create:
Use braces and dict(), key-value pairs are represented by colons, and key-value pairs are separated by commas
{< key1 >:<value1>,<key2>:<value2>,…,< Key n>:<value n>)

<Dictionary variable> = {<key1>:<value1>,<key2>:<value2>,…,<keyn>:<valuen>}
Get the value by key
<value> = <dictionary variable> [<key>]
Modify the corresponding value of the key (if the key does not exist, this operation is a new key-value pair)
<Dictionary variable>[<key>] = <value>

Note: Both the collection type and the dictionary type are represented by {}, but {} cannot be used to generate an empty collection, because {} is used to generate the dictionary type by default

2. Dictionary processing functions and methods

Insert picture description here

例
d = {
    
    "中国":"北京","美国":"华盛顿","法国":"巴黎"}
print("中国" in d)
print(d.keys())
print(d.values())
输出
True
dict_keys(['中国', '美国', '法国'])
dict_values(['北京', '华盛顿', '巴黎'])

Note: here d.keys() and d.values() return not a list type but a dictionary value or key type

Insert picture description here

例
d = {
    
    "中国":"北京","美国":"华盛顿","法国":"巴黎"}
print(d.get("中国","伊斯兰堡"))
print(d.get("巴基斯坦","伊斯兰堡"))
输出
北京
伊斯兰堡

3. Dictionary type application scenarios

Mapping is everywhere, key-value pairs are everywhere
-for example: counting the number of times the data appears, data is the key, and the number of times is the value
-the main function: express key-value pair data, and then manipulate them

Guess you like

Origin blog.csdn.net/weixin_44997802/article/details/108121122