当前位置:网站首页>Dictionaries and collections
Dictionaries and collections
2022-07-04 10:38:00 【She was your flaw】
Dictionaries and collections
One 、 Additions, deletions and modifications to the dictionary
1. Add and change
Dictionaries [ key ] = value - When the key exists, it is to modify the corresponding value of the corresponding key ; When the key does not exist, the key value pair is added
Dictionaries .setdefault( key , value ) - Add key value pair ( When the key exists, the original value will not be modified )
cat = {
'name': ' Beautiful ', 'age': 2, 'color': ' white '}
print(cat) # {'name': ' Beautiful ', 'age': 2, 'color': ' white '}
Add method 1
cat['breed'] = ' Blue cat '
print(cat) # {'name': ' Beautiful ', 'age': 2, 'color': ' white ', 'breed': ' Blue cat '}
cat['aihao'] = 'sheep'
print(cat) # {'name': ' Beautiful ', 'age': 2, 'color': ' white ', 'breed': ' Blue cat ', 'aihao': 'sheep'}
Add method 2
cat.setdefault('weight', 8)
print(cat) # {'name': ' Beautiful ', 'age': 2, 'color': ' white ', 'weight': 8}
modify
cat['age'] = 3
print(cat) # {'name': ' Beautiful ', 'age': 3, 'color': ' white '}
practice : stay students Add the key value pair corresponding to the score to the students who have no score in , The score value is zero
students = [
{
'name': 'stu1', 'tel': '1234', 'score': 89},
{
'name': 'stu2', 'tel': '465', 'score': 80},
{
'name': 'stu3', 'tel': '678'},
{
'name': 'stu3', 'score': 78},
{
'name': 'stu4', 'tel': '234'}
]
for new_students in students:
new_students.setdefault('score', 0)
print(students) # [{'name': 'stu1', 'tel': '1234', 'score': 89}, {'name': 'stu2', 'tel': '465', 'score': 80}, {'name': 'stu3', 'tel': '678', 'score': 0}, {'name': 'stu3', 'score': 78}, {'name': 'stu4', 'tel': '234', 'score': 0}]
- Delete - Delete key value pair
del Dictionaries 【 key 】 - Delete the key value pair corresponding to the specified key ( If the key does not exist, an error will be reported )
Dictionaries .pop( key ) - Take out the value corresponding to the specified key in the dictionary
print(cat) # {'name': ' Beautiful ', 'age': 3, 'color': ' white ', 'weight': 8}
del cat['color']
print(cat) # {'name': ' Beautiful ', 'age': 3, 'color': ' white ', 'weight': 8}
print(cat) # {'name': ' Beautiful ', 'age': 3, 'color': ' white ', 'weight': 8}
del cat['weight']
print(cat) # {'name': ' Beautiful ', 'age': 3, 'color': ' white ', 'weight': 8}
del_value = cat.pop('name')
print(del_value)
Two 、 Dictionary related operations and functions
- The relevant operation
Dictionary not supported +、*, Nor does it support size comparison operators , Only support ==、!=
in and not in - Dictionary in and not in The judgment is whether the key exists
key in Dictionaries
key not in Dictionaries
dic1 = {
'a': 10, 'b': 20, 'c': 30}
print(10 in dic1) # False
print('a' in dic1) # True
2. Correlation function
len
dict( data ) - 1) The data itself is a sequence
2) The elements in the sequence must be a small sequence with only two elements
3) The first element of a small sequence must be immutable data
data = [('a', 10), ('b', 20)]
print(dict(data)) # {'a': 10, 'b': 20}
data2 = ['ab', range(2), [10, 20]]
print(dict(data2)) # {'a': 'b', 0: 1, 10: 20}
‘’’
Dictionary into list / Tuples
‘’’
dic2 = {
'a': 10, 'b': 20, 'c': 30}
print(list(dic2)) # ['a', 'b', 'c']
‘’’
3. Dictionary related methods
Dictionaries .clear() - Empty dictionary
Dictionaries .copy - Copy the original dictionary to produce an identical new dictionary
Dictionaries .update( Sequence ) - Add all the elements in the sequence to the dictionary ( If it exists, it will cover ). The sequence must be a dictionary or a sequence that can be converted into a dictionary
items、keys、values
Dictionaries .keys() - Get all dictionary keys , Return a sequence ( Not a dictionary or tuple )
Dictionaries .value() - Get all the values of the dictionary , Return a sequence ( Not a dictionary or tuple )
Dictionaries .items() - Get all the key value pairs in the dictionary , Return a sequence ( Not a dictionary or tuple )
‘’’
data3 = {
'd': 100, 'e': 200}
dic2.update(data3)
print(dic2) # {'a': 10, 'b': 20, 'c': 30, 'd': 100, 'e': 200}
print(dic2.keys()) # dict_keys(['a', 'b', 'c', 'd', 'e'])
print(dic2.values()) # dict_values([10, 20, 30, 100, 200])
print(dic2.items()) # dict_items([('a', 10), ('b', 20), ('c', 30), ('d', 100), ('e', 200)])
‘’’
4. Dictionary derivation
{ Key expression : The expression of the value for Variable in Sequence }
{ Key expression : The expression of the value for Variable in Sequence if Conditional statements }
‘’’
practice : Exchange the keys and values of a dictionary through the derivation of the dictionary
'''{'a': 10, 'b': 201} --> {10:'a', 20, 'b'}'''
new_dic2= {
dic2[key]: key for key in dic2}
print(new_dic2) # Beautiful
3、 ... and 、 aggregate
1. What is a collection (set)
Collections are containers ; take {} As a sign of the container , Multiple elements are separated by commas :{ Elements 1, Elements 2, Elements 3,…}
The set is variable ; Sets are unordered ;
Elements : Immutable data 、 The element is the only ( It has the function of automatic weight removal )
1) Empty set
set1 = set()
print(type(set1), len(set1)) # <class 'set'> 0
2) Sets are unordered
print({
1, 2, 3} == {
3, 1, 2})
3) Elements must be immutable data
set2 = {
1, 'abc', (2, 3)}
print(set2)
# set3 = {1, 'abc', [2, 3]}
# print(set3) # Report errors !
# 4) The element is the only
set4 = {
1, 2, 3, 1, 1, 3}
print(set4) # {1, 2, 3}
- Addition, deletion, modification and query of set elements
- check - Traverse
for Variable in aggregate :
The loop body
nums = {
23, 90, 89, 78}
for x in nums:
print(x)
- increase
‘’’
aggregate .add( Elements ) - Add the specified element to the collection
aggregate .update( Sequence ) - Add all the elements in the sequence to the collection
‘’’
nums.add(45)
print(nums) # {45, 78, 23, 89, 90}
nums.update('abc')
print(nums) # {'a', 'b', 45, 78, 23, 89, 90, 'c'}
- Delete
‘’’
aggregate .remove( Elements ) - Deletes the specified element , If the element does not exist, an error will be reported
aggregate .discard( Elements ) - Deletes the specified element , If the element does not exist, no error will be reported
‘’’
nums.remove(89)
print(nums) # {'a', 'b', 45, 78, 'c', 23, 90}
nums.discard('a')
print(nums) # {45, 78, 'c', 23, 90, 'b'}
# nums.remove(100) # Report errors
nums.discard(100)
- Change - A collection cannot directly modify the value of an element , If you have to change it, delete the element you want to change , Add new elements
nums.discard('b')
nums.update('B')
print(nums)
3. Mathematical set operation :&( intersection )、|( Combine )、-( Difference set )、^( Symmetric difference set )、>/<( True subset )、>=/<=( A subset of )
nums1 = {
1, 2, 3, 4, 5, 6, 7}
nums2 = {
5, 6, 7, 8, 9}
- aggregate 1 & aggregate 2 – Get the common elements of two collections ( Get is in the set 1 It's gathering again 2 The elements inside )
print(nums1 & nums2) # {5, 6, 7}
- aggregate 1 | aggregate 2 – Get all the elements of the two sets
print(nums1 | nums2) # {1, 2, 3, 4, 5, 6, 7, 8, 9}
- aggregate 1 - aggregate 2 – Get collection 1 In addition to being included in the set 2 Parts other than middle
print(nums1 - nums2) # {1, 2, 3, 4}
print(nums2 - nums1) # {8, 9}
- aggregate 1 ^ aggregate 2 – Merge two sets , Remove the middle common part
print(nums1 - nums2) # {1, 2, 3, 4}
- A subset of ( It could be equal ) And true subsets ( It's really smaller than it )
aggregate 1 > aggregate 2 --> Judgment set 2 Is it a collection 1 The proper subset of
print({
10, 20, 30, 40} > {
1, 2}) # False
print({
10, 20, 30, 40} > {
10, 30}) # True
print({
10, 20, 30, 40} > {
10, 20, 30, 40}) # False
print({
10, 20, 30, 40} >= {
10, 20, 30, 40}) # True
Dictionary and set work
Define a list , Save in list 6 Student information ( Student information includes : full name 、 Age 、 achievement ( Single subject )、 Telephone 、 Gender ( male 、 Woman 、 Unknown ) )
nums = [{ 'name': 'student1', 'age': 18, 'math': 90, 'tel': 9832642, ' Gender ': ' male '}, { 'name': 'student3', 'age': 19, 'math': 98, 'tel': 1367687, ' Gender ': ' male '}, { 'name': 'student4', 'age': 15, 'math': 56, 'tel': 8736588, ' Gender ': ' Woman '}, { 'name': 'student5', 'age': 17, 'math': 98, 'tel': 1382363, ' Gender ': ' Woman '}, { 'name': 'student6', 'age': 19, 'math': 56, 'tel': 7486447, ' Gender ': ' male '}, { 'name': 'student7', 'age': 16, 'math': 46, 'tel': 5346535, ' Gender ': ' Unknown '} ]Count the number of failed students
a = nums b = 0 for x in a[2:]: s = x['math'] if s < 60: b += 1 print(b)Print the name of the failed student and the corresponding grade
a = nums for x in a[2:]: if x['math'] < 60: print(x['name'], x['math'])Print the mobile phone tail number is 8 The name of the student
for stu in list1:
if stu['tel'][-1] == '8':
print(' The tail number of the mobile phone is 8:', stu['name'])
Print the highest score and the corresponding student's name
b = nums[0]['math'] for x in nums[1:]: a = x['math'] if a > b: b = a print(' The highest :', b) for x in nums: if x['math'] == b: print(x['name'])Delete all students of Unknown Gender
new_list1 = [stu for stu in list1 if stu[' Gender '] != ' Unknown ']
print(new_list1)
- Sort the list by student grade from large to small ( Struggle for a moment , If you can't, just give up )
list1.sort(key=lambda item: item['math'], reverse=True)
print(list1)
Use three sets to represent the names of selected students in three disciplines ( A student can take multiple courses at the same time )
- How many students are there in total
- Find the number of people who chose only the first subject and the corresponding name
- Find the number of students who have chosen only one subject and the corresponding name
- Find the number of students who have chosen only two subjects and their corresponding names
- Find the number of students who have chosen three courses and their corresponding names
边栏推荐
- /*Rewrite the program, find the value of the element, and return the iterator 9.13: pointing to the found element. Make sure that the program works correctly when the element you are looking for does
- Write a program to judge whether the elements contained in a vector < int> container are 9.20: exactly the same as those in a list < int> container.
- Today's sleep quality record 78 points
- OSPF comprehensive experiment
- DDL language of MySQL database: create, modify alter, delete drop of databases and tables
- 【FAQ】华为帐号服务报错 907135701的常见原因总结和解决方法
- Latex error: missing delimiter (. Inserted) {\xi \left( {p,{p_q}} \right)} \right|}}
- uniapp---初步使用websocket(长链接实现)
- Crawl Zhejiang industry and trade news page
- Recursive method to achieve full permutation (C language)
猜你喜欢
![[Galaxy Kirin V10] [desktop] printer](/img/ab/066923f1aa1e8dd8dcc572cb60a25d.jpg)
[Galaxy Kirin V10] [desktop] printer

Debug:==42==ERROR: AddressSanitizer: heap-buffer-overflow on address
![[Galaxy Kirin V10] [desktop and server] FRP intranet penetration](/img/54/7d1b8b7b8226e2820635dd04b92d1c.jpg)
[Galaxy Kirin V10] [desktop and server] FRP intranet penetration
![[Galaxy Kirin V10] [server] NFS setup](/img/ed/bd7f1a1e4924a615cb143a680a2ac7.jpg)
[Galaxy Kirin V10] [server] NFS setup
![[Galaxy Kirin V10] [desktop] cannot add printer](/img/a6/28e4aa31e805a018e6db2b32ca1be0.jpg)
[Galaxy Kirin V10] [desktop] cannot add printer

【Day1】 deep-learning-basics

Write a thread pool by hand, and take you to learn the implementation principle of ThreadPoolExecutor thread pool
![[FAQ] summary of common causes and solutions of Huawei account service error 907135701](/img/73/c4ee842475f05e2e67297fcac68779.png)
[FAQ] summary of common causes and solutions of Huawei account service error 907135701

MFC document view framework (relationship between classes)

The time difference between the past time and the present time of uniapp processing, such as just, a few minutes ago, a few hours ago, a few months ago
随机推荐
Work order management system OTRs
[Galaxy Kirin V10] [desktop] build NFS to realize disk sharing
Write a program to judge whether the two arrays are equal, and then write a similar program to compare the two vectors.
Button wizard business running learning - commodity quantity, price reminder, judgment Backpack
Article publishing experiment
Knapsack problem and 0-1 knapsack problem
When I forget how to write SQL, I
Ruby time format conversion strftime MS matching format
Recursion and divide and conquer strategy
System. Currenttimemillis() and system Nanotime (), which is faster? Don't use it wrong!
Write a thread pool by hand, and take you to learn the implementation principle of ThreadPoolExecutor thread pool
Application and Optimization Practice of redis in vivo push platform
Latex arranges single column table pictures in double column format articles
Occasional pit compiled by idea
按键精灵打怪学习-识别所在地图、跑图、进入帮派识别NPC
Network connection (III) functions and similarities and differences of hubs, switches and routers, routing tables and tables in switches, why do you need address translation and packet filtering?
[Galaxy Kirin V10] [desktop and server] FRP intranet penetration
Leetcode48. Rotate image
Evolution from monomer architecture to microservice architecture
[testing theory] thinking about testing profession