当前位置:网站首页>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
边栏推荐
- Rhcsa day 9
- [Galaxy Kirin V10] [server] system partition expansion
- Write a program that uses pointers to set all elements of an int array to 4.18: 0.
- [Galaxy Kirin V10] [server] system startup failed
- Knapsack problem and 0-1 knapsack problem
- What is devsecops? Definitions, processes, frameworks and best practices for 2022
- DDL statement of MySQL Foundation
- Software sharing: the best PDF document conversion tool and PDF Suite Enterprise version sharing | with sharing
- Error C4996 ‘WSAAsyncSelect‘: Use WSAEventSelect() instead or define _ WINSOCK_ DEPRECATED_ NO_ WARN
- Write a program to judge whether the two arrays are equal, and then write a similar program to compare the two vectors.
猜你喜欢
Two way process republication + routing policy
Rhcsa day 10 operation
Linked list operation can never change without its roots
On binary tree (C language)
Introduction to extensible system architecture
From programmers to large-scale distributed architects, where are you (2)
From programmers to large-scale distributed architects, where are you (I)
Basic principle of servlet and application of common API methods
Vs201 solution to failure to open source file HPP (or link library file)
[Galaxy Kirin V10] [desktop] printer
随机推荐
Evolution from monomer architecture to microservice architecture
DDL language of MySQL database: create, modify alter, delete drop of databases and tables
TS type gymnastics: illustrating a complex advanced type
[advantages and disadvantages of outsourcing software development in 2022]
leetcode1229. Schedule the meeting
Si vous ne connaissez pas ces quatre modes de mise en cache, vous osez dire que vous connaissez la mise en cache?
如果不知道這4種緩存模式,敢說懂緩存嗎?
system design
Four characteristics and isolation levels of database transactions
uniapp---初步使用websocket(长链接实现)
If you don't know these four caching modes, dare you say you understand caching?
[Galaxy Kirin V10] [server] soft RAID configuration
Talk about scalability
【Day2】 convolutional-neural-networks
/*The rewriter outputs the contents of the IA array. It is required that the type defined by typedef cannot be used in the outer loop*/
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] cannot add printer
BGP ---- border gateway routing protocol ----- basic experiment
Legion is a network penetration tool
Number of relationship models