Articles Catalogue
3. Dictionaries
3.1 Characteristics
- Dictionary is the most flexible built-in data type used in python outside the list
- A dictionary is a variable data type
- The difference between list and list
- List order, dictionary disorder
- Lists access elements by index, and dictionaries access elements by key
- Basic Dictionary Format
dic={key1:value1,key2:value2,......keyn:valuen}
- Values can be of any data type, but keys can't be, they must be immutable data types, that is, keys must be hashed.
- supplement
- Kohashi: immutable
- Not Hash: Variable
- Characteristic
- Key: value, key-value pairs connected by colons
- key: value, an element of a dictionary
- Keyvalue pairs are separated by commas
- The whole dictionary is wrapped in {}
3.2 Creation
Empty Dictionary
>>> dic={} >>> type(dic) <class 'dict'>
Multivariate Dictionary
info = {'id':31901001,'name':'Sheep','sex':'boy'} >>> dic=dict(id=1001,name='sheep',age=16) >>> dic {'id': 1001, 'name': 'sheep', 'age': 16}
Strong turn (use of zip)
zip() key=('id','name','age') value=(1001,'sheep',16) tp=dict(zip(key,value)) print(tp,type(zip),type(tp)) #{'id': 1001, 'name': 'sheep', 'age': 16} #<class 'type'> <class 'dict'>
Create a dictionary through the fromkeys method
- format
dict.fromkeys(seq,val=None)
- Create and return a dictionary
- Use the elements in sep as keys in a dictionary
- val is the initial value of all keys in the dictionary and does not provide a default of None.
dic=dict.fromkeys('Tom') print(dic) #{'T': None, 'o': None, 'm': None} dic=dic.fromkeys(['name','sex','age'],33) print(dic) #{'name': 33, 'sex': 33, 'age': 33}
3.3 Common Operations
3.3.1 Increase
- Add key-value pairs directly (dic[key]=value)
- By using the variable name ['key']='value'
- If key does not exist, create a new key-value pair [key:value]
- Update the value if it exists
- By using the variable name ['key']='value'
dic={} dic['id'] = 1001 dic['name'] = 'sheep' dic['age'] = 16 print(dic) #{'id': 1001, 'name': 'sheep', 'age': 16} dic['name'] = 'Tom' print(dic) #{'id': 1001, 'name': 'Tom', 'age': 16}
- Example: Simple add queries
lis=[{'id':1001,'name':'Tom'},{'id':1002,'name':'Sheep'}] def sel_name(id): id=int(id) for i in lis: if i['id']==id: return i['name'] return 1; def add_lis(id,name): id=int(id) lis.append({'id':id,'name':name}) while True: a = input('-----------\n1.Adding members\n2.adopt id Search for personnel\n0.Exit and view\n-----------\n') a = int(a) if a == 1: id = input('Please enter Add id:') while True: if sel_name(id) == 1: break else: print('id Has been registered!!!') id = input('Please re-enter id: ') name = input('Please enter the added name:') add_lis(id, name) print('Added Successfully') elif a == 2: id = input('Please enter id: ') if sel_name(id) == 1: print("No one can find it.") else: print('name:', sel_name(id)) elif a == 0: print(lis) exit() else: print('Input error!') st=input('Press any key to continue!')
-
dic.update(dic)
Update key: value pairs in dictionary dic to dict
- If the keys of the two dictionaries are completely different, add dic's key values to dict altogether.
- If there are two identical keys, update
dic={'id':1001,'name':'sheep'} dic2={'sex':'boy','name':'tom'} dic2.update(dic) print(dic2) #{'sex': 'boy', 'name': 'sheep', 'id': 1001}
3.3.2 Delete
-
dict.pop
- Format: dict.pop(key[,default])
- If key exists in dict, delete and return dict[key]
- If it does not exist, the default value is returned, the default value is not given, and the error is reported.
dic2={'sex': 'boy', 'name': 'sheep', 'id': 1001} dic2.pop('sex') print(dic2) #{'name': 'sheep', 'id': 1001} dic2.pop('age') #Report errors a=dic2.pop('sex') print(a) #boy
- Format: dict.pop(key[,default])
-
dict.popitem()
- Then delete a pair of key-value pairs
- Tuples with return values
dic2={'sex': 'boy', 'id': 1001,'name': 'sheep'} a=dic2.popitem() print(dic2,a) #{'sex': 'boy', 'id': 1001} ('name', 'sheep')
-
del dict[]
Delete base
dic2={'sex': 'boy', 'id': 1001,'name': 'sheep'} del dic2['sex'] print(dic2) #{'id': 1001, 'name': 'sheep'}
-
dict.clear()
empty
dic2={'sex': 'boy', 'id': 1001,'name': 'sheep'} dic2.clear() print(dic2) #{}
3.3.3 Change
- directly modify
dic={'sex': 'boy', 'id': 1001,'name': 'sheep'} dic['id']=1002 print(dic) #{'sex': 'boy', 'id': 1002, 'name': 'sheep'}
- dict.setdefault()
- Build, exist, unchanged, return the value in the dictionary
- No, add the corresponding key-value pair to the dictionary and return the corresponding value.
dic={'sex': 'boy', 'id': 1001,'name': 'sheep'} print(dic.setdefault('id',999)) print(dic) print(dic.setdefault('age',16)) print(dic) ########### 1001 {'sex': 'boy', 'id': 1001, 'name': 'sheep'} 16 {'sex': 'boy', 'id': 1001, 'name': 'sheep', 'age': 16}
3.3.4 check
- Access to dictionary values
- Access value through the key of the dictionary
print(dic['id']) #Error reporting if return does not exist
- dict.get() accesses value
- The grammatical format dict.get(key[,default])
- Uncertainty about whether a key exists in a dictionary and want to manipulate it, such as getting a value --> get method
- When key does not exist, no exception is thrown and None is returned.
dic={'sex': 'boy', 'id': 1001,'name': 'sheep'} print(dic.get('age')) #None print(dic.get('age',12)) #12
3.4 traversal
- dict.keys() returns all keys
- dict.values() returns all values
- dict.items() returns key and values
dic={'sex': 'boy', 'id': 1001,'name': 'sheep'} print(dic.keys()) print(dic.values()) print(dic.items()) #dict_keys(['sex', 'id', 'name']) #dict_values(['boy', 1001, 'sheep']) #dict_items([('sex', 'boy'), ('id', 1001), ('name', 'sheep')])
for i in dic.items(): print(i[0],':',i[1]) #sex : boy #id : 1001 #name : sheep for i,j in dic.items(): print(i,':',j) #Ibid.
#Give an example li=[22,33,55,66,88,45,95,99,79] dic={'>=60':[],'<60':[]} for i in li: if i>=60: dic['>=60'].append(i) else: dic['<60'].append(i) print(dic)
4. Sets
set()
4.1 Characteristics
- disorder
- Not repeatable
- Immutable
- Internal elements are hashable
- The set itself is not hashing
- Unit data sets enclosed in {}
- purpose
- Duplicate removal
- Relational testing
4.2 Creation
4.2.1 Creation of Empty Sets
>>> st=set() >>> st set() >>> st={} >>> type(st) <class 'dict'>
4.2.2 Multivariate Set Creation
>>> st={1,2,5,6,9} >>> type(st) <class 'set'>
4.3 Strong Turn
>>> li= ['city','cc','aa'] >>> st=set(li) >>> type(st) <class 'set'> >>> st {'cc', 'city', 'aa'} >>> s='city' >>> st=set(s) >>> st {'c', 't', 'i', 'y'} >>> dic={'id':101,'name':'tom'} >>> st=set(dic) >>> st {'id', 'name'} >>> lu=list(dic) >>> lu ['id', 'name']
4.4 Basic Operations
4.4.1 Increase
- set.add()
- set.update()
4.4.2 Delete
- set.pop() Deletes one of the smallest sorted elements
- set.discard() removes elements that do not exist and will report errors
- set.remove()
- del set
>>> li=[1,2,3,4,5,6,'a','b'] >>> s=set(li) >>> s.pop() 1 >>> s.discard('a') {2, 3, 4, 5, 6, 'b'} >>> s.remove(2) {3, 4, 5, 6, 'b'}
Irreversible and unverifiable
4.5 traversal
li=['a','b','c',1,2,3] s=set(li) for a,b in enumerate(s,0): print('(',a,b,')',end=' ') #( 0 1 ) ( 1 2 ) ( 2 3 ) ( 3 b ) ( 4 a ) ( 5 c )
4.6 Set Basic Operations
4.6.1 subset
>>> a=set('asd') >>> b=set('dsa') >>> a,b ({'d', 'a', 's'}, {'d', 'a', 's'}) >>> a==b True >>> a>b False
4.6.2 intersection
- &
- set.intersection
a=set('accqa') b=set('gqebgeb') print(a&b) #{'q'} print(a.intersection(b)) #{'q'}
4.6.3 Union
- |
- set.union()
print(a|b) #{'q', 'b', 'e', 'g', 'c', 'a'} print(a.union(b)) #{'q', 'b', 'e', 'g', 'c', 'a'}
4.6.4 difference set
-
- set.diference()
print(a-b) print(a.difference(b)) #{'c', 'a'}