In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
How to use the practical application of dictionaries in daily life to introduce the knowledge of dictionaries in Python, many novices are not very clear about this. In order to help you solve this problem, the following editor will explain it in detail. People with this need can come and learn. I hope you can get something.
I. Preface
If you have a list and you need to change the name "xiaoWang", you need to change the code with the corresponding index value.
NameList = ['xiaoZhang',' xiaoWang', 'xiaoLi'] nameList [1] =' xiaoxiaoWang
If the order of the list changes, it is as follows:
NameList = ['xiaoWang',' xiaoZhang', 'xiaoLi']
At this point, you need to modify the subscript to complete the name modification.
NameList [0] = 'xiaoxiaoWang'
Is there a way to store multiple data and locate the desired element with easy access to the element? This is the dictionary.
Introduction of dictionaries
Dictionaries, like lists, can store multiple data.
When you find an element in the list, it is based on the subscript.
When looking for an element in the dictionary, it is based on the 'name' (that is, the colon: the preceding value, such as' name', 'id',' sex' in the above code).
Each element of the dictionary consists of two parts, key: value. For example, 'name':' monitor', where 'name'' is the key and 'monitor' is the value.
Access values based on key
Example:
Info = {'name':' monitor', 'id':100,' sex':'f', 'address':' Earth Asia, Beijing, China'} print (info ['name']) print (info [' address'])
Running result:
If you access a key that does not exist, an error will be reported:
> > info ['age'] Traceback (most recent call last): File ", line 1, in KeyError:' age'
When we are not sure whether a key exists in the dictionary and want to get its value, we can use the get method and set the default value.
> age = info.get ('age') > age #' age' key does not exist, so age is None > type (age) > age = info.get ('age', 18) # if the key' age' 'does not exist in info, return the default value 18 > print (age) 18 # run result
1. Common operations of dictionaries 1
Add elements info = {'name':' monitor', 'sex':'f',' address':' Asia, Beijing, China'} print ('id is:% d'%info ['id'])
Running result:
If the "key" is in the dictionary and does not exist when using the variable name [key] = data, then this element will be added.
Add a new element.
Info = {'name':' monitor', 'sex':'f',' address':' Asia, Beijing, China'} # print ('id is:% d'%info ['id']) # the program will run at the terminal, because the non-existent key newId = input (' please enter a new student ID') info ['id'] = newId print (' added id is:% d'%info ['id'])
Running result:
Please enter the new student number 188. the added id is: 188 to delete the element.
There are several ways to delete dictionaries:
Del
Clear ()
Del deletes the specified element
Info = {'name':' monitor', 'sex':'f',' address':' Asia Beijing, China'} print ('before deletion,% s'%info [' name']) del info ['name'] print (' after deletion,% s'%info ['name'])
Running result:
Del deletes the entire dictionary.
Info = {'name':'monitor',' sex':'f', 'address':'China'} print (' before deletion,% s'%info) del info print ('after deletion,% s'%info)
Running result:
Clear empties the entire dictionary.
Info = {'name':'monitor',' sex':'f', 'address':'China'} print (' before emptying,% s'%info) info.clear () print ('after emptied,% s'%info)
Running result:
Modify element
The data in each element of the dictionary can be modified as long as it is found through key.
Info = {'name':' monitor', 'id':100,' sex':'f', 'address':' Asia, Beijing, China'} newId = input ('Please enter a new student ID') info ['id'] = int (newId) print (' modified id is% d:'%info ['id'])
Running result:
two。 Common operations of dictionaries 2
Len ()
Measure the number of key-value pairs in the dictionary.
Dict= {"name": 'zahnsan','sex':'m'} print (len (dict))
Running result:
Keys
Returns a list of all the KEY of the dictionary.
Dict= {"name": 'zahnsan','sex':'m'} print (dict.keys ())
Running result:
Values
Returns a list of all the value of the dictionary.
Dict= {"name": 'zahnsan','sex':'m'} print (dict.values ())
Running result:
Items
Returns a list of all (keys, values) meta-ancestors.
Dict= {"name": 'zahnsan','sex':'m'} print (dict.items ())
Running result:
Third, traversing
Syntax: through for... In.: syntax structure, we can traverse strings, lists, tuples, dictionaries and other data structures.
Note: indentation of Python syntax
First take a look at how strings, lists, and tuples are traversed.
String traversal
> a_str = "hello itcast" > for char in a_str:. Print (char,end='')... H e l l o i t c a s t # run result
List traversal
> a_list = [1,2,3,4,5] > for num in a_list:. Print (num,end='')... 1 2 3 4 5 # running result
Tuple traversal
> a_turple = (1,2,3,4,5) > for num in a_turple:. Print (num,end= "") 1 2 3 4 5 # running result
Dictionary traversal
1. Traversing the dictionary's key (key)
2. Value (value) of the traversal dictionary
3. Traversing the entries (elements) of a dictionary
4. Traversal dictionary key-value (key-value pair)
5. Enumerate ()
Chars = ['averse,' baked, 'cached,' d'] for I, chr in enumerate (chars): print (I, chr)
Running result:
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
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.