Dict (dictionary)
Python built-in dictionary: dict support, Dict full name dictionary, in other languages also known as map, using key-value (Key-value) storage, with a very fast search speed.
Compared with list, Dict has the following features:
- The speed of finding and inserting is very fast and will not slow with the increase of key;
- It takes a lot of memory, and it wastes a lot of memory.
And the list is the opposite:
- The time to find and insert increases as the element increases;
- Small footprint and little wasted memory.
So, Dict is a way of exchanging space for time.
Dict can be used in many places where high-speed lookups are needed, almost everywhere in Python code, it is important to use dict correctly, and the first thing to keep in mind is that the Dict key must be an immutable object .
This is because Dict calculates the storage location of value based on key, and if each calculation of the same key results in a different result, the dict interior is completely chaotic. The algorithm for calculating the position by key is called the hash Algorithm (hash).
To ensure the correctness of the hash, the object as a key can not be changed. In Python, strings, integers, and so on are immutable, so you can safely use them as keys. The list is mutable and cannot be a key:
>>> key = [1, 2, 3]'a list'Traceback (most recent call last): " <stdin> " in <module>'list'
" "Dictionary: Contains <key, value> basic Operation" "my_dict= {'name':'Kumata',' Age': 20,' Location':'Zhuhai'}#Output Key valuePrint(my_dict['name']) #increase key pair valuemy_dict['Sex'] ='Mans'Print(my_dict)#to modify a value in a dictionarymy_dict[' Age'] = 21Print(my_dict)#Delete a key value pairdelmy_dict['Sex']Print(my_dict)#Traverse Dictionary forKey,valueinchMy_dict.items ():Print(Key,':', value)#Clear Dictionarymy_dict.clear ()Print(my_dict)
Set (SET)
Set is similar to Dict and is a set of keys, but does not store value. Because key cannot be duplicated, there is no duplicate key in set.
" "set is similar to Dict and is a set of keys, but does not store value. Because key cannot be duplicated, there is no duplicate key in set. To create a set, you need to provide a list as the input collection:" "S1= Set ([1,2,3,4,5])Print(S1)#{1, 2, 3, 4, 5}#repeating elements are automatically filtered in setS2 = Set ([1,1,2,3,3,4])Print(S2)#{1, 2, 3, 4}#add Element (key)S1.add (6)Print(S1)#{1, 2, 3, 4, 5, 6}S1.add (1)Print(S1)#{1, 2, 3, 4, 5, 6}#Remove (key) Delete elementS1.remove (6)Print(S1)#{1, 2, 3, 4, 5}
Examples of Python hash tables: Dict, set