python system learning dictionary and collection

Posted by SpinCode on Wed, 23 Feb 2022 08:49:43 +0100

Dictionaries

d = {key1 : value1, key2 : value2, key3 : value3 }
Keys must be unique, but values do not.
The value can take any data type, but the key must be immutable, such as string and number.

Modify dictionary

The way to add new content to the dictionary is to add new key / value pairs

tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
tinydict['Age'] = 8               # Update Age
tinydict['School'] = "Rookie tutorial"  # Add information
print ("tinydict['Age']: ", tinydict['Age'])
print ("tinydict['School']: ", tinydict['School'])
#tinydict['Age']:  8
#tinydict['School ']: rookie tutorial

Delete dictionary element

tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
del tinydict['Name'] # Delete key 'Name'
tinydict.clear()     # Empty dictionary
del tinydict         # Delete dictionary

Characteristics of dictionary keys

1) The same key is not allowed to appear twice. If the same key is assigned twice during creation, the latter value will be remembered;
2) Keys must be immutable, so you can use numbers, strings, or tuples instead of lists

Dictionary built-in functions & Methods

------------------------------Built in function---------------------------------------------
1 len(dict): calculate the number of dictionary elements, that is, the total number of keys.

 tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
 len(tinydict)
 3

2 str(dict): output dictionary, which is represented by a string that can be printed.

tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
str(tinydict)
"{'Name': 'Runoob', 'Class': 'First', 'Age': 7}"

3 type(variable)
Returns the type of the input variable. If the variable is a dictionary, it returns the dictionary type.

>>> tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
>>> type(tinydict)
<class 'dict'>

------------------------------------Built in method--------------------------------------
1 dict.clear(): delete all elements in the dictionary
2 dict.copy(): returns a shallow copy of a dictionary
3 dict.fromkeys(): create a new dictionary, use the elements in seq sequence as the keys of the dictionary, and val is the initial value corresponding to all keys of the dictionary
4 dict.get(key, default=None): return the value of the specified key. If the key is not in the dictionary, return the default value set by default
5 key in dict: returns true if the key is in dict, otherwise returns false
6 dict.items(): returns a view object as a list
7 dict.keys(): returns a view object
8 dict.setdefault(key, default=None): similar to get(), but if the key does not exist in the dictionary, the key will be added and the value will be set to default
9 dict.update(dict2): update the key / value pairs of dict2 dictionary into dict
10 dict.values(): returns a view object
11 pop(key[,default]): delete the value corresponding to the key given in the dictionary, and the return value is the deleted value. The key value must be given. Otherwise, the default value is returned.
12 popitem(): randomly return and delete the last pair of keys and values in the dictionary

-------------------------------##Assemble--------------------------------------

aggregate

You can use braces {} or set() function to create a set. Note: to create an empty set, you must use set() instead of {}, because {} is used to create an empty dictionary.
parame = {value01,value02,...} or set(value)

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)                      # What is demonstrated here is the de duplication function
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket                 # Quickly determine whether an element is in a collection
True
>>> 'crabgrass' in basket
False
>>> # The operation between two sets is shown below
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # Elements contained in set a but not in set b
{'r', 'd', 'b'}
>>> a | b                              # All elements contained in set a or b
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # Both sets a and b contain elements of
{'a', 'c'}
>>> a ^ b                              # Elements not included in both a and b
{'r', 'd', 'b', 'm', 'z', 'l'}

Basic operations of collection

1,Add element
s.add(x)#If the element already exists, no action will be taken
>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.add("Facebook")
>>> print(thisset)
{'Taobao', 'Facebook', 'Google', 'Runoob'}

s.update(x)#Elements can be added, and the parameters can be lists, tuples, dictionaries, etc
>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.update({1,3})
>>> print(thisset)
{1, 3, 'Google', 'Taobao', 'Runoob'}
>>> thisset.update([1,4],[5,6])  
>>> print(thisset)
{1, 3, 4, 5, 6, 'Google', 'Taobao', 'Runoob'}

2,Removing Elements 
s.remove(x)
>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.remove("Taobao")# An error will occur if the does not exist
>>> print(thisset)
{'Google', 'Runoob'}

s.discard( x )
>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.discard("Facebook")  # Does not exist, no error will occur
>>> print(thisset)
{'Taobao', 'Google', 'Runoob'}

s.pop() 
#The pop method of the set will arrange the set disorderly, and then delete the first element on the left of the disorderly arranged set.

3,Calculate the number of collection elements
len(s)

4,Empty collection
s.clear()

5,Determine whether the element exists in the collection
x in s
 Judgment element x Is it in the collection s In, there is a return True,No return False. 
>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> "Runoob" in thisset

Complete list of collection built-in methods

1. add() adds an element to the collection
2. clear() removes all elements from the collection
3. copy() copies a collection
4. difference() returns the difference set of multiple sets
5,difference_update() removes the element in the collection, which also exists in the specified collection.
6. discard() deletes the specified element in the collection
7. intersection() returns the intersection of sets
8,intersection_update() returns the intersection of sets.
9. isdisjoint() determines whether the two collections contain the same element. If it does not return True, otherwise it returns False.
10. issubset() determines whether the specified set is a subset of the method parameter set.
11. issuperset() determines whether the parameter set of the method is a subset of the specified set
12. pop() randomly removes elements
13. remove() removes the specified element
14,symmetric_difference() returns a collection of elements that are not duplicated in the two collections.
15,symmetric_difference_update() removes the same elements in the current set as in another specified set, and inserts different elements in another specified set into the current set.
16. union() returns the union of two sets
17. update() adds elements to the collection

Topics: Python