Python - dictionary

   (1) Getting to know the dictionary for the first time   

       A dictionary is an unordered variable sequence of " key-value pairs " . Each element in the dictionary is a " key-value pair" , including: " key object " and " value object " . The " key object " can be used to quickly obtain, delete, and update the corresponding " value object " .
    A typical dictionary definition: a = {'name':'gaoqi', 'age':18, 'job':'programmer'}

        In the list, we find the corresponding object through the " subscript number " . Find the corresponding " value object " through the " key object " in the dictionary .

  • A " key " is any immutable data such as: integers, floats, strings, tuples. 

  •  However, variable objects such as lists, dictionaries, and collections cannot be used as " keys " .

  • " Key " is not repeatable.

  • " Value " can be arbitrary data and can be repeated.

(2) Creation of dictionary

Create a dictionary object     through {} , dict()

Specific code:
a ={'name':'baibi','age':18,'job':'programmer'}
b =dict(name='baibi',age=18,job='programmer')
a = dict([("name","baibi"),("age",18)])
c = {}  #空的字典对象
d = dict()  #空的字典对象

Create a dictionary object through zip()

Specific code:

k = ['name','age','job']
v = ['baibi',18,'teacher']
d = dict(zip(k,v))
print(d) #{'name': 'baibi', 'age': 18,'job': 'techer'}

Create a dictionary with empty values ​​​​by fromkeys

f = dict.fromkeys(['name','age','job'])
print(f)  #结果:{'name': None, 'age':None, 'job': None}

(3) Access to dictionary elements

Get " value " by [ key ] .

If the key does not exist, an exception is thrown
a ={'name':'baibi','age':18,'job':'programmer'}
b = a['name']
print(b)

The " value " is obtained by the get() method .

 The advantage is: if the specified key does not exist, return None ; you can also set the object returned by default when the specified key does not exist. Recommendation: Use get() to get the " value object "
a ={'name':'baibi','age':18,'job':'programmer'}
b = a.get('name')
c = a.get('gender','不存在')
print(b)
print(c)

List all key-value pairs

a ={'name':'baibi','age':18,'job':'programmer'}
b = a.items()
print(b)  #dict_items([('name', 'baibi'),('age', 18), ('job', 'programmer')])

List all keys, list all values

a ={'name':'baibi','age':18,'job':'programmer'}
k = a.keys()
v = a.values()
print(k)  #dict_keys(['name', 'age','job'])
print(v)  #dict_values(['baibi', 18,'programmer'])

len() the number of key-value pairs

a ={'name':'baibi','age':18,'job':'programmer'}
num = len(a)
print(num)  #3

Check if a " key " is in the dictionary

a ={'name':'baibi','age':18,'job':'programmer'}
print("name" in a)  #True

(4) Adding, modifying, and deleting dictionary elements

   Add " key-value pairs " to the dictionary .

If the " key " already exists, the old key-value pair will be overwritten; if the " key " does not exist, a new " key-value pair " will be added.

a ={'name':'baibi','age':18,'job':'programmer'}
a['address']='毛列街道1号院'
a['age']=16
print(a)
#{'name': 'baibi', 'age': 16, 'job':'programmer', 'address': '毛列街道1号院'}

use update()

Add all key-value pairs in the new dictionary to the old dictionary object. If the key is duplicated, it will be directly overwritten

a ={'name':'gaoqi','age':18,'job':'programmer'}
b ={'name':'gaoxixi','money':1000,'gender':'男的'}
a.update(b)
print(a)
#{'name': 'gaoxixi', 'age': 18, 'job':'programmer', 'money': 1000, 'gender': '男的'}

Deletion of elements in a dictionary

      You can use the del() method; or clear() to delete all key-value pairs; pop() deletes the specified key-value pair and returns the corresponding " value object ".

a ={'name':'baibi','age':18,'job':'programmer'}
del(a['name'])
print(a)       #{'age': 18, 'job':'programmer'}
age = a.pop('age')
print(age)     #18

drink()

        Randomly delete and return the key-value pair. Dictionaries are " unordered mutable sequences " , so there is no concept of first element, last element; popitem pops up random items, because dictionaries do not have " last element " or other concepts of order. This method is very efficient if you want to remove and process items one by one (since you don't have to get the list of keys first).
Specific code:
a ={'name':'gaoqi','age':18,'job':'programmer'}
r1 = a.popitem()
r2 = a.popitem()
r3 = a.popitem()
print(a)    #{}

(5) Sequence unpacking

       Sequence unpacking works with tuples, lists, and dictionaries. Sequence unpacking allows us to easily assign values ​​to multiple variables.
When sequence unpacking is used for dictionaries, the default is to operate on " keys " ; if you need to operate on key-value pairs, you need to use items() ; if you need to operate on " values " , you need to use values();

 

s = {'name':'baibi','age':18,'job':'teacher'}
name,age,job=s #默认对键进行操作
print(name)    #name
name,age,job=s.items() #对键值对进行操作
print(name)    #('name', 'baibi')
name,age,job=s.values() #对值进行操作
print(name)    #baibi
 

(6) Table data is stored and accessed using dictionaries and lists

Name age salary City
Zhao Gao 18 30000 Beijing
Wang An 19 20000 Shanghai
 
r1 = {"name":"赵高","age":18,"salary":30000,"city":"北京"}
r2 = {"name":"王安","age":19,"salary":20000,"city":"上海"}
tb = [r1,r2]
#获得第二行的人的薪资
print(tb[1].get("salary"))
#打印表中所有的的薪资
for i in range(len(tb)): # i -->0,1,2
    print(tb[i].get("salary"))
#打印表的所有数据
for i in range(len(tb)):
    print(tb[i].get("name"),tb[i].get("age"),tb[i].get("salary"),tb[i].get("city"))

(7) The core underlying principles of the dictionary

        The core of the dictionary object is a hash table. A hash table is a sparse array (an array that always has blank elements), and each unit of the array is called a bucket . Each bucket has two parts: a reference to the key object and a reference to the value object.
        Since all buckets have the same structure and size, we can read the specified bucket through the offset .

 

The underlying process of putting a key-value pair into a dictionary
a = {}
a [ "name" ]= "libai"
Assume that after the dictionary a object is created, the length of the array is 8:

 

      We need to put the key-value pair "name" = "libai" into the dictionary object a . The first step is to calculate the hash value of the key "name". It can be calculated by hash() in Python .
print(bin(hash("name")))
#-0b100001100010000110000100011111010111110010110100010111111111101
       Since the length of the array is 8 , we can take the rightmost 3 digits of the calculated hash value as the offset, which is "101" , which is the number 5 in decimal . We check whether the corresponding bucket is empty at offset 5 . If empty, put the key-value pair in. If it is not empty, take the right 3 bits as the offset in turn, that is, "100" , which is the number 4 in decimal . Then check whether the bucket with offset 4 is empty. Put the key-value pair into it until you find an empty bucket . The flow chart is as follows:

 

expansion
Python will expand according to the degree of congestion of the hash table. " Expansion " refers to : creating a larger array and copying the original content to the new array
middle. When it is close to 2/3, the array will expand.

 

The underlying process of looking up a " key-value pair " based on a key
    It is easy to understand how a key-value pair is stored in an array, and the value object is obtained according to the key object.
Usage summary : 1
Dictionaries are expensive in memory, and the typical space is traded for time.
2
Key lookups are fast
3
Adding new key-value pairs to the dictionary may cause expansion, resulting in a change in the order of the keys in the hash table. Therefore, do not modify the dictionary while iterating over it.
4
key must be hashable
1
Numbers, strings, tuples, all hashable
2
Custom objects need to support the following three points
1 support hash() function
2 Support for checking equality via the __eq__() method
3 If a==b is true, then hash(a)==hash(b) is also true

Guess you like

Origin blog.csdn.net/qq_63976098/article/details/131552077