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 > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains the "case analysis of common methods of Python dictionary". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "case analysis of common methods of Python dictionary".
Dictionary addition and modification methods make use of [] processing
When we see [], we think of using square brackets to get the index of members (elements) in lists and tuples, or using indexes to modify members (elements), but the use of square brackets in dictionaries is not the same.
There is no concept of index in dictionaries
Value is added and modified through key in the dictionary.
Dict ['name'] =' Jack'
The operation of adding or modifying is determined by the existence of the key in the dictionary; if there is a corresponding key in the dictionary, the modify operation is performed. If there is no corresponding key, the added operation is performed.
Examples are as follows:
User = {'name':' Neo', 'age': 18} user [' birthday'] = '2000-01-01'print (user) # the execution result is as follows: # > > {' name': 'Neo',' age': 18, 'birthday':' 2000-01-01'} # there is no key for birthday Add operation user = {'name':' Neo', 'age': 18} user [' name'] = 'Jack'print (user) # the result is as follows: # > > {' name': 'Jack',' age': 18, 'birthday':' 2000-01-01'} # > key with name, and execute the built-in function update that modifies the operation dictionary
The function of the update function: add a new dictionary. If the new dictionary has the same key as the original dictionary, the value of the key will be overwritten by the value of the new dictionary.
Usage of the update function: dict.update (new_dict), which has no return value; new_dict is the new dictionary
Examples are as follows:
Default_dict = {} new_dict = {'name':' Neo'} default_dict.update (new_dict) print (default_dict) # the execution result is as follows: # > {'name':' Neo'} user = {'name':' Neo', 'age': 18,' birthday': '2000-01-01'} user_jack = {'name':' Jack', 'age': 17,' birthday': '2001-12-12' The execution result of 'sex':' man'} user.update (user_jack) print (user) # is as follows: # > > {'name':' Jack', 'age': 17,' birthday': '2001-12-12, the built-in function setdefault of' sex': 'man'} dictionary
Function of setdefault: get the value of a key. If key does not exist in the dictionary, key will be added and value will be set as the default value.
Usage of the setdefault function: dict.setdefault (key,value). The parameter key is the value of the key,value to be obtained and the corresponding key. If the key does not exist, the corresponding key is stored in the default value of the dictionary.
Examples are as follows:
User = {'name':' Neo', 'age': 18} value = user.setdefault (' name', 'Jack') print (the content of the'\ 'user\' dictionary is:', user,';\ 'setdefault\' the value of\ 'name\' of the\ 'user\' dictionary obtained is:', value) # the execution result is as follows: # > 'user' dictionary: {' name': 'Neo',' age': 18} The name' value of the 'user' dictionary' obtained by setdefault' is: Neouser = {'name':' Neo', 'age': 18} value = user.setdefault (' birthday', '1990-01-01') print ('\ 'user\' dictionary content is:', user,' \ 'setdefault\' the value of\ 'birthday\' of\ 'user\' dictionary obtained is:', value) # the execution result is as follows: # > 'user' dictionary content is: {' name': 'Neo',' age': 18, 'birthday':' 1990-01-01}; the value of birthday' of 'user' dictionary' obtained by setdefault' is: 1990-01-01 about dictionary notes again
Each key in the dictionary must be unique, and it is absolutely impossible to have two identical kay.
There is no limit to the amount of data in the dictionary.
The value in the dictionary can be objects and custom objects of built-in data types in any Python.
Try to do a little exercise
Cinemas classify recent films by war movies, romance movies and science fiction movies and store them in the following dictionary
Books_dict = {"warfare": ["Flag of my parents", "Whisperwind", "Red Baron", "Save Private Ryan"], "love": ["Roman Holiday", "palpitating Heart", "time and Space Traveler", "Angel Love Beauty", "Angel City", "hapless Love God"], "science_fiction": [wandering Earth "," Cosmic pursuit " "time Administration", "Destiny Administration"]}
There are several fantasy films that have not been stored, the Lord of the Rings, Harry Potter, the Legend of the Night and Pirates of the Caribbean, put them in the dictionary and count how many films need to be scheduled for release.
The code example is as follows:
Films_dict = {'warfare': [' Flag of my parents', 'Wind Whisperer', 'Red Baron', 'Save Private Ryan'], 'love': [' Roman Holiday', 'heart throbbing', 'time and space travelers', 'Angels love beauty', 'City of Angels', 'hapless Love God'], 'science_fiction': [' wandering Earth', 'Cosmic pursuit' Film_fiction = {'fantasy':' [Lord of the Rings', 'Harry Potter', 'Legend of the Night', 'Pirates of the Caribbean']} films_dict.update (film_fiction) print (films_ Lord of the Rings, Harry Potter, Legend of the Night) # > 'Pirates of the Caribbean'] warfare= films_dict ['warfare'] love = films_dict [' love'] science_fiction = films_dict ['science_fiction'] fantasy = films_dict [' fantasy'] count_films = len (warfare) + len (love) + len (science_fiction) + len (fantasy) print ('there are {} movies to be scheduled' .format (count_films) # the results are as follows: # > > A total of 18 films need to be scheduled to obtain key and value of dictionaries
Keys function in Dictionary
The function of the keys function: get all the keys of the current dictionary (key)
The use of the keys function: dict.keys (), which does not need to pass parameters and returns a pseudo-list of key collections
Examples are as follows:
User = {'name':'Neo',' age':18, 'birthday':'2000-01-01'} print (user.keys ()) # the execution result is as follows: # > dict_keys (['name',' age', 'birthday']) # > dict_keys does not have all the functions of the list, cannot get members (elements) through the index, and cannot add, modify, etc.
So how to modify the pseudo-list of dict_keys to make it have the relevant functions of the list? Let's take a look at the following example
User = {'name':'Neo',' age':18, 'birthday':'2000-01-01'} user_list = list (user.keys ()) user_list.append ('sex') print (user_list) # the result is as follows: # > [' name', 'age',' birthday', 'sex'] # in this way, dict_keys has the values function in the dictionary of all the functions in the list
The function of the values function: to get the values of all key-value pairs in the current dictionary (value)
The use of the values function: dict.values (), which does not need to pass parameters and returns a pseudo-list of value collections
Examples are as follows:
User = {'name':'Neo',' age':18, 'birthday':'2000-01-01'} print (user.values ()) # the execution result is as follows: # > dict_values ([' Neo', 18, '2000-01-01]) # > > dict_values does not have all the functions of a list, cannot get members (elements) through the index, and cannot add, modify, etc.
So how to modify the pseudo-list of dict_keys to make it have the relevant functions of the list? Let's take a look at the following example
User = {'name':'Neo',' age':18, 'birthday':'2000-01-01'} user_list = list (user.values ()) user_list.append ('man') print (user_list) # the execution result is as follows: # > [' Neo', 18, '2000-01-01,' man'] # thus, dict_values has all the functions of getting key in the list dictionary
The acquisition method of []
In the index, [] can get the corresponding value of the index; if you add "=" and value, that is to modify the value of the index. The way to get the value through "[]" in the dictionary is the same as the index, as long as the "=" and the value are not written, you are getting the value of the current key.
Dictionary + []: input key in square brackets without assignment, that is, get it.
Returns the value value corresponding to key
Examples are as follows:
User = {'name':'Neo',' age':18, 'birthday':'2000-01-01'} name = user ['name'] print (the value of'\ 'user\' dictionary name is:', name) # the execution result is as follows: # > 'user' dictionary name: Neo
Get acquisition method of Dictionary built-in function
The function of the get function: get the value of the currently specified key
Usage of the get function: dict.get (key,default = Node). Key is the key,default that needs to get value and the default value returned when key does not exist. The default is Node. We can also customize it.
Note:
When we try to use a custom default (dict.get (key, default=' key does not exist'), an error message for TypeError: dict.get () takes no keyword arguments is generated.
Solution:
The get ("key", default=Node) method does not add default=. Deleting this writing does not affect the usage logic, but if it causes an error, we can try to pass in the value or the corresponding variable prompt directly.
Examples are as follows:
User = {'name':'Neo',' age':18, 'birthday':'2000-01-01'} default_info = 'name = user.get (' name', default_info) print (name) # the result is as follows: # > Neouser = {'name':'Neo',' age':18, 'birthday':'2000-01-01'} default_info = 'name = user.get (' sex') Default_info) print (name) # the execution result is as follows: # > the currently passed key does not exist
The difference between [] and get
[] if the obtained key does not exist, an error will be reported directly
The get function returns the default value if the obtained key does not exist
In the process of development, it is recommended to give priority to using the get () function.
Delete and copy clear function of dictionary
The function of the clear function: to clear the existing data in the current dictionary
Usage of clear function: dict.clear (), no parameters, no return value
Examples are as follows:
User = {'name':'Neo',' age':18, 'birthday':'2000-01-01'} user.clear () print (user) # the execution result is as follows: # > {} pop function
The function of the pop function: delete the key specified in the dictionary, return its result, and report an error if the key does not exist.
The usage of the pop function: dict.pop (key), delete the key specified in parentheses and return the value corresponding to this key.
Examples are as follows:
User = {'name':'Neo',' age':18, 'birthday':'2000-01-01'} pop_value = user.pop ('birthday') print ('\ 'pop_value\' deleted\ 'value\' of\ 'birthday\' is:', pop_value,'\ 'user\' dictionary is:' User) # the execution result is as follows: # > 'pop_value'' value' is: 2000-01-01 'user' dictionary is: {' name': 'Neo',' age': 18} del function
Function of the del function: delete the key specified in the dictionary or delete the entire dictionary
Usage of del function: del dict ['key'], del dict
Examples are as follows:
User = {'name':'Neo',' age':18, 'birthday':'2000-01-01'} del user ['birthday'] print ('\ 'user\' dictionary is:', user) # the execution result is as follows: # > 'user' dictionary is: {' name':'Neo', 'age':18} del userprint (user) # execution result is as follows: # > NameError: name' user' is not defined. Did you mean: 'super'?# the user variable here has been completely deleted from the copy function
The function of the copy function: copy the current dictionary to a new dictionary, which does not share the same memory address as the original dictionary.
Usage of the copy function: dict.copy (), which takes no arguments and returns a dictionary with exactly the same content but a different memory address.
Examples are as follows:
Old_user = {'name':' Neo', 'age': 18,' birthday': '2000-01-01'} new_user = old_user.copy () print (old_user) print (new_user) # the execution result is as follows: # > > {'name':' Neo', 'age': 18,' birthday': '2000-01-01'} # > > {'name':' Neo', 'age': 18 'birthday':' 2000-01-01'} print (the memory address of'"old_user" is:', id (old_user),'"new_user" is:', id (new_user)) # the execution result is as follows: the memory address of "old_user" is: 140464840867968 "new_user": the memory address of 140464841281088in and not in in the dictionary
In the study of lists and tuples, we have also come into contact with the use of the member operators in and not in. Unlike lists and tuples, member operators can only determine whether key exists in the dictionary.
Examples are as follows:
Test_dict = {'name':' Neo'} print ('name' in test_dict) print (' name' not in test_dict) # the result is as follows: # > True# > False
In fact, the existence of a member can also be determined by using the get function in the dictionary. An example is as follows:
Test_dict = {'name':' Neo'} print (bool (test_dict.get ('name') # the execution result is as follows: # > True
Note: when you use the get function to determine whether a member (element) exists, the Boolean value returned is False when the value of key is empty and 0.
Popitem function in Dictionary
The function of the popitem function: delete the key-value pair at the end of the current dictionary and return it
Usage of the popitem function: dict.popitem, no need to pass parameters. Returns the deleted key-value pair, wrapped in tuples, with 0 index key and 1 index value.
Examples are as follows:
User = {'name':' Neo', 'age': 18,' birthday': '2000-01-01'} user_popitem = user.popitem () print (user_popitem) print ('\ 'user_popitem\' 0 index element is:', user_popitem [0]) print ('\ 'user_popitem\' 1 index element is:' User_popitem [1]) # the execution result is as follows: # > 'user_popitem' 0 index element is: birthday# >' user_popitem' 1 index element is: 2000-01-01
Note: if the dictionary is empty, the error will be reported directly.
User = {'name':' Neo', 'age': 18,' birthday': '2000-01-01'} user.clear () print (user.popitem ()) # the execution result is as follows: # > > KeyError: 'popitem (): dictionary is empty' Thank you for your reading. The above is the content of "example Analysis of Common methods in Python Dictionary". After the study of this article I believe that we have a deeper understanding of the common methods of Python dictionary example analysis of this problem, the specific use of the situation still needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.