1. Preface
A dictionary is the only type of mapping in Python that stores data in the form of key-value pairs (key-value). Python computes the hash function of key and determines the storage address of value based on the result of the calculation, so the key of the dictionary must be hashed. A hash indicates that a key must be an immutable type, such as a number, a string, a tuple.
The key of the dictionary must be unique, but the value does not have to be. The value can take any data type, but the key must be immutable, such as a string, a number, or a tuple.
A list is an ordered combination of objects, and a dictionary is a collection of unordered objects. The difference between the two is that the elements in the dictionary are accessed by keys, not by offsets.
2. Define a dictionary
Each key value of the dictionary (key=>value) pairs with a colon (:) split, each pair is separated by a comma (,), and the entire dictionary is included in curly braces ({})
dic = { 'name' : 'nanliangrexue','age':18}print(dic)#输出{'name': 'nanliangrexue', 'age': 18}
3. Adding and deleting dictionaries
Add a new key-value pair to the original dictionary
dic = { 'name' : 'nanliangrexue','age':18}dic['gender'] = 'male'print(dic)#输出{'name': 'nanliangrexue', 'age': 18, 'gender': 'male'}
By deleting
- del: remove a key-value pair from the dictionary
dic = { 'name' : 'nanliangrexue','age':18}del dic['age']print(dic)#输出{'name': 'nanliangrexue'}
- pop (): removes a key-value pair from the dictionary and returns the deleted key-value pair
dic = { 'name' : 'nanliangrexue','age':18}print(dic.pop('age'))print(dic)#输出18{'name': 'nanliangrexue'}
- Popitem (): randomly deletes a pair of keys and values in the dictionary and returns the deleted key-value pairs as tuples
dic = { 'name' : 'nanliangrexue','age':18}print(dic.popitem())print(dic)#输出('age', 18){'name': 'nanliangrexue'}
dic = { 'name' : 'nanliangrexue','age':18}del dicprint(dic)#输出报错,因为字典已经被删除Traceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'dic' is not defined
- Clear (): Empty Dictionary
dic = { 'name' : 'nanliangrexue','age':18}dic.clear()print(dic)#输出{}
Change
To modify a key/value pair already in the dictionary, simply reassign the key value of the key value pair you want to modify.
dic = { 'name' : 'nanliangrexue','age':18}dic['age'] = 28print(dic)#输出{'name': 'nanliangrexue', 'age': 28}
Check
- Key Value Key Lookup, if the search does not error
dic = { 'name' : 'nanliangrexue','age':18}print(dic['name'])print(dic['age'])print(dic['gender'])#输出'nanliangrexue'18Traceback (most recent call last): File "<stdin>", line 1, in <module>KeyError: 'gender'
- Get lookup, if the lookup does not return to none, will not error
dic = { 'name' : 'nanliangrexue','age':18}print(dic.get('name'))print(dic.get('age'))print(dic.get('gender'))#输出'nanliangrexue'18None
4. The method of the dictionary
- Dict.fromkeys (key, value)
To create a new dictionary, the key must be an iterative data type (list, tuple, String, collection, dictionary), and the value is the default value for each key-value pair
dict1 = dict.fromkeys([1,2,3],'china')dict2 = dict.fromkeys('name','china')print(dict1)print(dict2)#输出{1: 'china', 2: 'china', 3: 'china'}{'n': 'china', 'a': 'china', 'm': 'china', 'e': 'china'}
- Dict.get (Key, Default=none)
Returns the value of the specified key if the value does not return the default value in the dictionary
dic = { 'name' : 'nanliangrexue','age':18}print(dic.get('name'))print(dic.get('gender'))print(dic.get('gender','您所查找的键值不存在!'))#输出'nanliangrexue'None'您所查找的键值不存在!'
- Dict.items ()
Returns an array of traversed (key, value) tuples as a list
dic = { 'name' : 'nanliangrexue','age':18}print(dict1.items())#输出dict_items([(1, 'china'), (2, 'china'), (3, 'china')])
- Dict.keys ()
Returns all keys in a dictionary as a list
dic = { 'name' : 'nanliangrexue','age':18}print(dict1.keys())#输出dict_keys([1, 2, 3])
- Dict.setdefault (Key, Default=none)
is similar to get () and also looks for the value of the specified key, but if the lookup key does not exist in the dictionary, the key is added and the value is set to default
dic = { 'name' : 'nanliangrexue','age':18}print(dic.setdefault('name'))print(dic.setdefault('gender','male'))print(dic)#输出'nanliangrexue''male'{'name': 'nanliangrexue', 'age': 18, 'gender': 'male'}
- Dict.update (DICT2)
Add the key value pairs of the dictionary dict2 to the Dict1, that is, merge Dict1 and dict2 into a dictionary.
dic1 = { 'name' : 'nanliangrexue','age':18}dic2 = { 'gender' : 'male'}dic1.update(dic2)print(dic1)#输出{'name': 'nanliangrexue', 'age': 18, 'gender': 'male'}
- Dict.values ()
Return all values in a dictionary as a list
dic = { 'name' : 'nanliangrexue','age':18}print(dic.values())#输出dict_values(['nanliangrexue', 18])
5. The traversal of a dictionary
- Traversing the Dictionary key
dic = { 'name' : 'nanliangrexue','age':18}for key in dic.keys(): print(key)#输出'name''age'
- Iterate through the value in the dictionary
dic = { 'name' : 'nanliangrexue','age':18}for value in dic.values(): print(value)#输出'nanliangrexue'18
- Simultaneously traverse the key and value in the dictionary, returning in tuples
dic = { 'name' : 'nanliangrexue','age':18}for item in dic.items(): print(item)#输出('name', 'nanliangrexue')('age', 18)
"Sixth" in Python Learning: dictionaries in Python and the methods they have