In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "what are the knowledge points of the python dictionary". In the daily operation, I believe that many people have doubts about the knowledge points of the python dictionary. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the questions of "what are the knowledge points of the python dictionary?" Next, please follow the editor to study!
The definition of a dictionary
Dictionary (dict) is a more commonly used data type, which uses key-value pairs to store data. The key (key) must be an immutable object and cannot be repeated, and the string is usually used as the key; value (value). The underlying structure of the dictionary is a hash table (hash table), which can quickly look up key to get value, which is a data structure that trades space for time.
The advantage of a dictionary is that it is fast to find and add data and does not slow down as the number of keys increases; the disadvantage is that it consumes memory.
The disadvantage of lists is that the speed of finding and inserting data slows down as the number of elements increases; the advantage is memory savings.
It is also important to note that python 3.6 rewrites the internal algorithm of the dictionary, so in version 3.6 and later of python, dictionaries are ordered, in the order in which elements are added. Previous versions of python3.6 dictionaries are unordered. The following is the sample code for validation:
D = dict () d ["name"] = "Mike" d ["age"] = 20d ["money"] = 8000d ["height"] = 180for key, value in d.items (): print (key, value) # can run the above code verification many times, and the order of each print is the same as that of the dictionary, indicating that it is in order. S = {"Mike", 20Magne8000180} for i in s: print (I) # can run the above code verification many times, each time the printing order is different, indicating that it is out of order. The creation of a dictionary
Empty dictionary, a pair of curly braces.
D = {} print (type (d)) out:
A dictionary of key-value pairs, separated by colons and surrounded by curly braces.
D = {'name':'Mike'} print (type (t)) out:
A dictionary of multiple key-value pairs, surrounded by curly braces and separated by commas.
D = {"name": "Mike", "age": 20, "money": 8000, "height": 8000} print (type (d)) out:
Other types are converted to dictionaries.
Key = ('name',' age', 'money',' height') value = ("Mike", 20,180) d = dict (zip (key, value)) # the most common way to combine two lists or tuples into a dictionary, remember print (d) list1= [('a list, 1), ('breadth, 2), (' censor, 3)] dict2 = dict (list1) print (dict2) # nested list or tuple Each element is two child elements, which can be converted into a dictionary, which is not as convenient as the zip method out: {'name':' Mike', 'age': 20,' money': 8000, 'height': 180} {' a': 1, 'baked: 2,' centering: 3}
Dictionary derivation, although there is a dictionary derivation, it is rarely used in practice, so I will not repeat it here. The most commonly used dict (zip (key,value)) method in building dictionaries should be skillfully mastered.
Create dictionaries with keys but no values or dictionaries with different keys with the same values.
Key = ('name',' age', 'money',' height') dict1 = dict.fromkeys (key) # have no value print (dict1) dict2 = dict.fromkeys (key, 0) # different keys have the same value print (dict2) out: {'name': None,' age': None, 'money': None,' height': None} {'name': 0,' age': 0, 'money': 0,' height': 0}
Access to dictionaries
Access the key value through square brackets. If you access a key that does not exist, an error will be reported.
Dict1 = {"name": "Mike", "age": 20, "money": 8000, "height": 8000} print (dict1 ["money"]) # print (dict ['country']) exception TypeError:' type' object is not subscriptableout:8000
Access the key value with the get method. The default value can be preset. If the key does not exist, the default value is returned without adding a key-value pair; if the key exists, the original value is returned.
Dict1 = {"name": "Mike", "age": 20, "money": 8000, "height": 8000} print (dict1.get ('name')) print (dict1.get (' country', 'USA')) print (dict1) # get method does not add key pairs dict1 [' country'] = 'UK'print (dict1.get (' country', 'USA') out:MikeUSA {' name': 'Mike',' age': 20, 'money': 8000) 'height': 180} UK
Access the key value with the setdefault method. The default value can be preset. If the key does not exist, the default value will be returned and the key-value pair will be added. If the key exists, the original value will be returned.
Dict1 = {"name": "Mike", "age": 20, "money": 8000, "height": 8000} print (dict1.setdefault ('name',' George')) print (dict1) print (dict1.setdefault ('country',' USA')) print (dict1) out:Mike {'name':' Mike', 'age': 20,' money': 8000, 'height': 180} USA {' name': 'Mike',' age': 20, 'money': 8000 'height': 180,' country': 'USA'}
The addition and revision of dictionaries
Add or modify key-value pairs directly through square brackets.
Dict1 = {"name": "Mike", "age": 20, "money": 8000, "height": 8000} dict1 ['coutry'] =' USA' # dictionary without this key means adding key value to dict1 ['age'] = 21 # dictionary with this key means modification value print (dict1) out: {' name': 'Mike',' age': 21, 'money': 8000,' height': 180, 'coutry':' USA'}
Add or modify key-value pairs through the update method.
Dict1 = {"name": "Mike", "age": 20, "money": 8000, "height": 8000} dict1.update ({'country':' USA'}) # Dictionary does not have this key means adding key value to dict1.update ({'age': 21}) # Dictionary with this key means modification value print (dict1) out: {' name': 'Mike',' age': 21, 'money': 8000,' height': 180 'country': 'USA'}
Deletion of dictionaries
Del: delete elements according to key, or you can delete the dictionary itself directly.
Dict1 = {"name": "Mike", "age": 20, "money": 8000} del dict1 ['money'] print (dict1) del dict1out: {' name': 'Mike',' age': 20, 'height': 180}
Pop method: deletes the specified key and returns a value; an error will be reported if the specified key does not exist.
Dict1 = {"name": "Mike", "age": 20, "money": 8000, "height": 8000} print (dict1.pop ('money')) print (dict1) out:8000 {' name': 'Mike',' age': 20, 'height': 180}
Popitem method: randomly deletes a key-value pair and returns it.
Dict1 = {"name": "Mike", "age": 20, "money": 8000, "height": 8000} print (dict1.popitem ()) print (dict1) out: ('height', 180) {' name': 'Mike',' age': 20, 'money': 8000}
Clear method: clear the contents of the dictionary, keep the dictionary itself, and use this method first when you need to empty the dictionary in the loop body, rather than creating a new dictionary, because the new one is relatively expensive.
Dict1 = {"name": "Mike", "age": 20, "money": 8000, "height": 8000} dict1.clear () print (dict1) out: {}
Dictionary query
In the key of the dictionary
Dict1 = {"name": "Mike", "age": 20, "money": 8000, "height": 8000} print ('name' in dict1) print (' Mike' in dict1) out:TrueFalse
Perform in operations on the values of the dictionary
Dict1 = {"name": "Mike", "age": 20, "money": 8000, "height": 8000} print ('name' in dict1.values ()) print (' Mike' in dict1.values ()) out:FalseTrue
The built-in method of the dictionary
Dictionary built-in methods are very rich, in addition to the above mentioned fromkeys, get, setdefault, update, pop, popitem, clear, there are some sequence general methods len, copy, dictionary-specific methods items (), keys (), values ().
Len, which returns the element length of the dictionary
Copy, create a copy of the dictionary, the content is the same, id is different. (note: deepcopy should be used for nested structures)
Here are some examples.
Dict1 = {"name": "Mike", "age": 20, "money": 8000, "height": 180} print (len (dict1)) dict2 = dict1.copy () print (id (dict1), id (dict2)) out:42721528676224 2721528676288
Items, and returns the key-value pair of the dictionary
Dict1 = {"name": "Mike", "age": 20, "money": 8000, "height": 180} for key, value in dict1.items (): print (key, value, end='\ t') out:name Mike age 20 money 8000 height 180
Keys, returns the key of the dictionary
Dict1 = {"name": "Mike", "age": 20, "money": 8000, "height": 180} for key in dict1.keys (): print (key, dict1 [key], end='\ t') out:name Mike age 20 money 8000 height 180
Values, which returns the dictionary value. For a case, please see the previous query of the dictionary-in the value of the dictionary.
The nested structure of dictionaries
Dictionary keys are immutable objects, do not use nested structures. The value of the dictionary is a mutable object and can be any nested structure.
Key = [i for i in range (5)] value = [(I, j) for i in range (1 key,value 5) for j in range (10 dict1 15)] dict1 = dict (zip (key,value)) print (dict1) out: {0: (1, 10), 1: (1, 11), 2: (1, 12), 3: (1, 13), 4: (1, 14)} this ends the study of "what are the knowledge points of python dictionaries"? I hope I can solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.