In the previous section, we learned about dictionary methods. In this chapter, we will learn about hybrid dictionaries, dictionary traversal and dictionary derivation.
The so-called mixed dictionary means that the data stored in the dictionary is a mixture of various types. The keys need to be immutable data types, but the values can be objects of any type.
Let’s first look at a mixed dictionary:
my_dcit={'Xiao Ming': ['Height: 170cm', 'Weight: 65kg'], 'Xiao Li': 'Love learning, love sports', 'Xiaohua': ('Residence: Suzhou', 'Birthplace :Shanghai')}
The values of this dictionary are composed of lists, strings and tuples. We can access this mixed dictionary through the method in the previous section. Look at the following piece of code
my_dcit={'Xiao Ming': ['Height: 170cm', 'Weight: 65kg'], 'Xiao Li': 'Love learning, love sports', 'Xiaohua': ('Residence: Suzhou', 'Birthplace :Shanghai')}print('Access key='Xiao Ming'->',my_dcit['Xiao Ming']) print('Access key='Xiaohua'->',my_dcit['Xiaohua'])print('Access key='Xiaohua'->',my_dcit['Xiaohua'])print('itmes() Method:',my_dcit.items())#Access pr overall int('keys() method:',my_dcit.keys())#Only accessed all keyprint('values() method:',my_dcit.values())#Only accessed valueprint('get() method:' ,my_dcit .get('Xiao Ming')) #get method to access the specified key my_dcit.pop('Xiao Ming') #This step is the pop() method, which will delete the paired elements with key = 'Xiao Ming' print('pop() method My_dict after:',my_dcit)#Check the deleted dictionary
Take a look at the output:
Access key='Xiao Ming'->['Height: 170cm', 'Weight: 65kg'] Access key='Xiaohua'->Love learning, love sports access key='Xiaohua'->('Residence: Suzhou ','Birthplace: Shanghai') itmes() method: d ict_items([('Xiao Ming',['Height: 170cm','Weight: 65kg']),('Xiao Li','Loves learning and sports'),('Xiaohua',('Residence: Suzhou ','Birthplace: Shanghai'))])keys() method: d ict_keys(['Xiao Ming','Xiao Li','Xiao Hua'])values() method:dict_values([['Height: 170cm','Weight: 65kg'],'Love learning, love sports',(' Place of residence: Suzhou','born Place: Shanghai')]) get() method: ['Height: 170cm', 'Weight: 65kg'] my_dict after pop() method: {'Xiao Li': 'Love learning, love sports', 'Xiaohua ':('Residence: Suzhou', 'Birthplace: Shanghai')}
When we use dictionaries, we often need to traverse the dictionary. We usually use a for loop to traverse all the keys in the dictionary.
Let’s take a look at traversal access in general:
>>>my_dict={1001:'Xiaoming',1002:'Xiaohua',1003:'Xiaozhang'}>>>foriinmy_dict:print(i,my_dict[i])#Output key and the value corresponding to the key 1001Xiao Ming 1002 Xiaohua 1003 Xiao Zhang
We will also use the items() method to get pairs of elements when getting the object.
>>>my_dict={1001:'Xiao Ming',1002:'Xiao Hua',1003:'Xiao Zhang'}>>>foriinmy_dict.items():print(i)(1001,'Xiao Ming')(1002,' Xiaohua')(1003,'Xiao Zhang')
This method of access is a pair of data in the opposite dictionary, and the output result is output in the form of a tuple. At the same time, the key and value of each traversal can be directly obtained through loop traversal.
>>>my_dict={1001:'Xiao Ming',1002:'Xiao Hua',1003:'Xiao Zhang'}>>>fori,jinmy_dict.items():print('corresponding key:',i,'corresponding value :',j) Corresponding key: 1001 Corresponding value: Xiao Ming Corresponding key: 1002 Corresponding value: Xiao Hua Corresponding key: 1003 Corresponding value: Xiao Zhang
Finally, practice the dictionary traversal through exercises.
I have learned about list derivation before. Tuple derivation is similar to list derivation without much introduction, because dictionaries are relatively special. Here we will explain dictionary derivation.
Let’s look at a simple usage first.
>>>my_dict={i:'dotcpp'foriinrange(1,5)}>>>my_dict{1:'dotcpp',2:'dotcpp',3:'dotcpp',4:'dotcpp'}
Here we take a look at the structure of the dictionary derivation. The first part is equivalent to using 'dotcpp' to assign the value object of each i. We can also define a list first and assign the value in the list to it.
>>>my_list=[10,20,30,40,50]>>>my_dict={i:my_list[i]foriinrange(1,5)}>>>my_dict{1:20,2:30,3: 40,4:50}
Look at the picture below:
When using dictionary derivation, the main problem is the matching of keys and values. After we learn the function later, we can use the zip() function to more conveniently combine dictionaries. We will not introduce it too much here.
The user is required to enter the total assets, for example: 3000, then the shopping cart list is displayed, and the total amount of the items in the shopping cart is calculated. If the total amount of items is greater than the total assets, it will prompt that the account balance is insufficient. Otherwise, the purchase is successful. The shopping cart list is as follows: carts=[{name: bed, price: 1999, "num": 1}, {name: pillow, price: 10, " num ": 2}, {name: quilt, price: 20, " num”:1}].
The solution is at the end.
Dictionaries are a relatively commonly used data structure when learning Python. However, due to its uniqueness, there may be relatively few words about dictionaries in competition questions, but more in Python course learning and inspections. When data storage We can use dictionaries to help us find the corresponding data accurately, and mastering lists and dictionaries proficiently can help us learn Python better.
carts=[{name:bed,price:1999,"num":1},{name:pillow,price:10,"num":2},{name:quilt,price:20,"num":1} ]. m=int(input())sum=0foriinrange(len(carts)):sum=carts[i]['price']*carts[i]['num']+sumifm>=sum:print('Purchase successful ')else:print('Account balance insufficient')