Lecture 28: Core concepts and use cases of dictionary objects in Python

Article directory

    • 1. The core concept of dictionaries in Python
      • 1.1. What is a dictionary
      • 1.2. Features of the dictionary
      • 1.3. Why use a dictionary
    • 2. Dictionary creation
      • 2.1. Using curly braces to create a dictionary
      • 2.2. Call the dict function to create a dictionary
      • 2.3. Call the formkeys method of the dict function to create a dictionary
    • 3. Dictionary lookup operation
      • 3.1. Use square brackets to query the Value of the specified Key
      • 3.2. Call the get method to query the value of the specified Key
      • 3.3. Use the in and not in operators to query whether the Key is in the dictionary
    • 4. The Value of the Key in the dictionary can be a sequence object

1. The core concept of dictionaries in Python

1.1. What is a dictionary

In Python, in addition to lists and tuples, dictionaries are also built-in data structures provided by Python. Dictionaries are variable data structures, and the elements in them are stored out of order. Objects of any type can be stored in dictionaries.

How the dictionary works:

The implementation principle of the dictionary is very similar to the principle of looking up the dictionary in reality. There are two ways to look up the dictionary in reality:

1) From the first page of the dictionary to the last page, search page by page until the corresponding word position is found. This method is the same as the way to find elements in the list. The disadvantage is that when there are more and more elements, Search efficiency will be very low.

2) First look up the page number of the dictionary where a certain word is located in the index navigation table of the dictionary, and then directly find the corresponding word on the qualified page. The advantage is that the search efficiency is very fast, and the query will not be reduced as the number of words in the dictionary increases. efficiency.

The principle of Python dictionary:

In the dictionary, there is no index concept. The query of the dictionary is generally based on the Key to query the Value. Each element in the dictionary is a Key-Value key-value pair. Among them, the Key is required to be unique in the entire dictionary, and the Value value can be repeated.

The principle of the dictionary is that the dictionary will call the hash function to calculate the storage location of the corresponding Value according to the specified Key, that is, the hash value of the Value, so as to obtain the value of the Value.

A diagram of a dictionary is as follows:

Multiple elements can be stored in a dictionary, each element is in the form of a key-value pair Key-Value, and the Key key is unique in the entire dictionary, the Value value can be repeated, and the dictionary will specify a Key through the hash function , and then calculate its storage location for the Value, so as to obtain the Value corresponding to the Key.

image-20220808223239509

1.2. Features of the dictionary

  • All elements in the dictionary are a key-value pair: Key-Value. The specified Key can always be mapped to a unique Value. Duplicate Keys are not available in the dictionary, but duplicate Values can exist.
  • The elements in the dictionary are stored out of order. Although the elements are created one by one in order when defining a dictionary, they are stored out of order in actual storage, because the core of the dictionary is the key-value pair, mainly through the corresponding Value, so the order is not important. The most important thing is the mapping of Key and Value.
  • The key in the dictionary must be an immutable object. Because when storing or searching for a key-value pair in a dictionary, the system will call the hash function to calculate the storage location of the Value based on the specified Key, that is, the hash value. For the specified Key, in order to ensure that the calculated hash The hash values are all the same, so Key is required to be an immutable object, because only immutable objects have a hash value.
  • Dictionaries can be dynamically scaled as needed. Elements in the dictionary can be dynamically added, deleted, and modified according to requirements, without declaring the capacity of the dictionary in advance.
  • Dictionaries take up a lot of memory. Because its query speed is very fast, it is equivalent to exchanging space for time.

1.3. Why use a dictionary

Let’s analyze the following scenario. There is a function of viewing personnel information in the system, in which you can see the corresponding contact number and email address of all people, as shown below:

image-20220808215510114

If you don’t use a dictionary, or use a list to store the information of each person in the above picture, you need to create a list for each field separately, and the query is also more complicated. First, you need to get the index of the name list where a person’s name is located , and then use this index to find the corresponding contact number in the phone list, the code is as follows:

name = ["Mr. Jiang", "Ms. Wang", "Mr. Zhang", "Mr. Liu", "Ms. Li"]
phone = ["15123654501", "17800236587", "18866369958", "19910785336", "15950276666"]

print(phone[name.index("Mr. Jiang")])
#Output result: 15123654501

It is certainly possible to store the information of each element in a list, but whether it is creating a list or querying, it is more complicated and error-prone. We must match the names and phone numbers of the personnel in their respective lists one by one, otherwise data will be generated. disordered phenomenon.

The final solution is to be able to store the name and contact number in a data structure, enter the name of the person, and return the mobile phone number. Based on this scenario, we can implement it through a dictionary.

Each element in the dictionary is in the form of a key-value pair. The key is the name of the person, and the value is the contact number. In this way, when the name is queried, the corresponding mobile phone number can be returned. The code is as follows:

#Store the person's name and contact number in the dictionary data structure, each element is a key-value pair, a person's name and mobile phone number are placed in one element, the name is the key, and the mobile phone number is value.
infophone = {<!-- -->
    'Mr. Jiang': '15123654501',
    'Ms. Wang': '17800236587',
    'Mr. Zhang': '18866369958',
    'Mr. Liu': '19910785336',
    'Ms. Li': '15950276666'
}

#At this time, it becomes very simple to query the mobile phone number of the person.
print(infophone['Mr. Jiang'])

#Output result: print(infophone['Mr. Jiang'])

2. Dictionary creation

2.1. Create a dictionary with curly braces

print({<!-- -->'username': 'jiangxl', 'password': '123456'})

'''
key: usuername
Value: jiangxl
key: password
Value: 123456
'''

#Output result: {'username': 'jiangxl', 'password': '123456'}

image-20220808232110898

Create an empty dictionary:

print({<!-- -->})

#Output result: {}

2.2. Call the dict function to create a dictionary

In addition to using curly braces to specify the creation of a dictionary, you can also call the dict function to create a dictionary. When using the dict function to create a dictionary, there are several methods, the commonly used ones are as follows:

1) Directly pass curly braces into the dict function to create a dictionary code

You can directly pass the code of curly braces to create a dictionary as a parameter into the dict function to create a dictionary.

print(dict({<!-- -->'username': 'jiangxl', 'password': '123456'}))

#Output result: {'username': 'jiangxl', 'password': '123456'}

2) Pass key=value keyword parameters in the dict function to create a dictionary

You can pass in keyword parameters in the dict function, and the format of the keyword is key = value to create a dictionary.

print(dict(username = 'jiangxl', password = '123456'))
'''
    username = 'jiangxl' will be converted into a dictionary format: username: jiangxl
'''
#Output result: {'username': 'jiangxl', 'password': '123456'}

3) Pass in the list in the dict function to create a dictionary

A list can be passed in as a parameter in the dict function, and each element in this list is a tuple, and each tuple must contain two elements, the first element is the key, and the second element is the value.

print(dict([("username", "jiangxl"),("password", "123456")]))
'''
In this method, a list is passed in as a parameter in the dict function, each element in the list must be a tuple, and each element must contain at least two elements
The first element is the key and the second element is the value.
For example ("username", "jiangxl"), after creating the dictionary is username: jiangxl
'''
#Output result: {'username': 'jiangxl', 'password': '123456'}

It is also possible to nest multiple tuples within a tuple:

print(dict((("username", "jiangxl"),("password", "123456"))))

4) Pass in the zip object in the dict function to create a dictionary

The dictionary can be created by passing in the tuple in the dict function. We can also call the zip object to compress the list into a tuple according to the incoming list, and finally pass the result to the dict function to complete the creation of the dictionary.

When using the zip function to reorganize a sequence, only two tuple sequences can be passed in. The elements of one tuple passed in are all Keys in the dictionary, and the elements of the second tuple are all Values in the dictionary. When compressed with When reorganizing, the elements of the same index will be placed in a tuple, that is, both Key and Value are in a tuple, and finally the creation of the dictionary can be completed.

zipdata = zip(("username","password"), ("jiangxl", '123456'))
'''
   Since the zip function will compress and reorganize the elements with the same index in multiple sequences, the first tuple sequence will fill in all the keys in the dictionary, and the second tuple sequence will fill in the values corresponding to the keys
'''
print(dict(zipdata))

#Output result: {'username': 'jiangxl', 'password': '123456'}

If the Value values in the dictionary are ordered integers, you can also pass in the range sequence in the zip function to create a dictionary.

print(list(zip("ACC",range(3))))

#Output result: [('A', 0), ('C', 1), ('C', 2)]

image-20220809155538107

2.3. Call the formkeys method of the dict function to create a dictionary

In addition to curly braces and the dict function to create a dictionary, you can also use the formkeys method in the dict function to create a dictionary.

When calling the formkeys method to create a dictionary, you can specify all the Keys in the dictionary through parameters. If only Key is specified, this method will set a default value of None for all Keys. You can also adjust the default Value value through parameters.

When calling the formkeys method, two parameters can be passed in. The first parameter is to specify all the Keys in the dictionary. When specifying the Key, it needs to be specified in the form of a list or tuple. The second parameter is to specify the default Value value. The default The value is None.

The fromkeys method can specify multiple Keys, but cannot specify multiple Values.

1) Only specify the default value of Key but not Value

#Do not specify the default value of Value, at this time the default value of Value is None.
print(dict. fromkeys(["username", "password"]))
print(dict. fromkeys(("username", "password")))
'''
The incoming parameter is a list: ["username", "password"], at this time all the elements in the list are a Key in the dictionary. When the default value of Value is not specified, the default value is None
'''
#Output results: {'username': None, 'password': None}

image-20220808235201491

2) Specify the default value of Value as haha

print(dict.fromkeys(["username", "password"], "haha"))
'''
The second parameter of the fromkeys method can specify the default value of Value, and after specifying, the Value of each Key is haha
'''
#Output result: {'username': 'haha', 'password': 'haha'}

image-20220808235220975

3. Dictionary lookup operation

The dictionary search operation is mainly to query the Value corresponding to a Key. There are three methods:

  • Directly use square brackets to query the Value value of the specified Key.
  • Call the get method to query the value of the specified Key.
  • You can also use the operators in and not in to query whether a Key exists in the dictionary.

3.1. Use square brackets to query the Value of the specified Key

#Define a dictionary
mydict = {<!-- -->'username': 'jiangxl', 'password': '123456'}

#Query the value corresponding to the username key in the dictionary
print(mydict['username'])

#Output result: jiangxl

image-20220809162800323

When the queried key does not exist in the dictionary, an exception will be thrown.

print(mydict['id'])

image-20220809162839492

3.2. Call the get method to query the value of the specified Key

Grammar format: dictionary.get('key name')

mydict = {<!-- -->'username': 'jiangxl', 'password': '123456'}
print(mydict. get('username'))

#Output result: jiangxl

When the queried Key does not exist in the dictionary, the get method will not throw an exception, but return the None value.

print(mydict. get('username'))
print(mydict. get('id'))

#Output result: None

image-20220809164440467

In addition, you can also set the default Value through parameters in the get method, so that when the queried Key does not exist in the dictionary, a humanized output will be returned.

print(mydict.get('id', 'There is no such Key in the dictionary'))

#Output result: there is no such Key in the dictionary

3.3. Use the in and not in operators to query whether the Key is in the dictionary

1) Use the in operator to query whether the specified Key is in the dictionary

print("username" in mydict)

#Output result: True

2) Use the not in operator to query whether the specified Key is not in the dictionary

print("id" not in mydict)

#Output result: True

4. The Value of the Key in the dictionary can be a sequence object

The Value value of the Key in the dictionary can be a string or a sequence object, as in the following case:

The company has newly established a technology center business department, including several small departments: development department, operation and maintenance department, and testing department. Each department has recently recruited several new colleagues.

Requirements: Save the list of colleagues in each department through a dictionary, and then count how many colleagues there are in each department.

Implementation idea:

  • The list of colleagues in each department is saved through the dictionary, the Key is the name of the department, and the Value is the list of all colleagues. Since there are multiple values, these objects are stored in a list.
  • According to the key name, the list of personnel in each department can be found. Since the name of each person is stored in a list, the number of elements in the list can be calculated through the len function, so that you can know how many colleagues there are in each department.
#Use a dictionary to store the list of personnel in each department
technology_center = {<!-- -->
    'develop_dep': ['Director Wang', 'Xiao Ming', 'Xiao Hong', 'Xiao Lan', 'Xiao Wang', 'Xiao Bai', 'Xiao Wu', 'Xiao Zhang'],
    'test_dep': ['Director Li', 'Xiao Gao', 'Xiao Li', 'Xiao Fei', 'Xiao Tian', 'Xiao Xia'],
    'ops_dep': ['Director Jiang', 'Xiao Zhao', 'Xiao Nan']
}

# Get the list of personnel for each department
develop_dep = technology_center['develop_dep']
test_dep = technology_center['test_dep']
ops_dep = technology_center['ops_dep']

#Total number of people in technology center
count_tech = len(develop_dep) + len(test_dep) + len(ops_dep)

#Define a formatting rule
techformat = 'Total technology center: {tech} people\
 ①New recruits in the development department: {dev} people\
 ②New recruits in the test department: {test} people\
 ③New recruits in the operation and maintenance department: {ops} people'

print(techformat. format(tech = count_tech,
                        dev = len(develop_dep),
                        test = len(test_dep),
                        ops = len(ops_dep)))

image-20220811114202019