python Foundation: basic data type three (dict), is and = =, encoding and decoding

1. dictionary

1.1 introduction to dictionary

Dict is the only mapping data type in python. It consists of key value pairs enclosed by {}. In dict, the key is unique. When saving, a memory address is calculated according to the key, and then the key value is saved in the address. This algorithm is called hash algorithm. Therefore, remember that the key in the key value stored in dict must be hash capable. If you don't know what is hashable, you can remember it in this way temporarily, and what can be changed is not hashable, then hashable means immutable. This is to accurately calculate the memory address.

Known hash (immutable) data types: int, str, tuple, bool non hash (mutable) data types: list, dict, set


{key1: value1, key2: value2....}

Note: the key must be immutable (hashable), value is not required, and any type of data can be saved.

# legitimate
dic = {123: 456, True: 999, "id": 1, "name": 'sylar', "age": 18, "stu": ['Handsome
//Brother', 'Mei Yu'], (1, 2, 3): 'Gentiana'}
print(dic[(1, 2, 3)])
# Wrongful
# dic = {[1, 2, 3]: 'Jay Chou'} # list It is variable.. Can not act as key
# dic = {{1: 2}: "Ha ha ha"} # dict is variable. It can't be a key
dic = {{1, 2, 3}: 'Interesting'} # set It is variable., Can not act as key

The data saved by dict is not saved in the order we added it, but in the order of hash table. Hash table is not continuous, so it cannot be sliced. It can only get the data in dict through key.

1.2 dictionary addition, deletion, modification and other related operations

1.2.1 increase

dic = {}
dic['name'] = 'Zhou Runfa' # If dict This doesn't appear in key, Will add key-value Group
Merge into dict
dic['age'] = 18

# If dict There's no such thing in key-value. Can pass setdefault Set default dic.setdefault('Li Jiacheng') # You can also set values to Chinese style. dic.setdefault("Li Jiacheng", "Real estate") # If dict Already exists in. that setdefault Will not Starting work


1.2.2 delete

ret = dic.pop("jay")

del dic["jay"] print(dic)

# Random deletion. ret = dic.popitem()

# Clear all content in dictionary dic.clear()

1.2.3 modification

dic = {"id": 123, "name": 'sylar', "age": 18}
dic1 = {"id": 456, "name": "Gentiana", "ok": "wtf"}
dic.update(dic1) # hold dic1 Content in updated to dic in. If key Duplicate name. Then modify the replacement. If it doesn't existstay key, Then add.

1.2.4 query

Query the general key to find the specific data

# print(dic['sylar']) # Report errors
print(dic.get("sylar")) # None
print(dic.get("sylar", "A kind of B")) # A kind of B

1.2.5 other relevant operations

dic = {"id": 123, "name": 'sylar', "age": 18, "ok": "Ke Hou"}

print(dic.keys()) # dict_keys(['id', 'name', 'age', 'ok']) No matter what it is.Whenbecome list Come on for key in dic.keys():    print(key)
print(dic.values()) # dict_values([123, 'sylar', 18, 'Ke Hou']) Like sample. Also when list Come on for value in dic.values():    print(value)
print(dic.items()) # dict_items([('id', 123), ('name', 'sylar'), ('age',18), ('ok', 'Ke Hou')]) So is this Dong list. Just list What is in the suit is tuple for key, value in dic.items(): # ?? This is deconstruction    print(key, value)
# deconstruction a, b = 1, 2 print(a, b)
(c, d)
= 3, 4 print(c, d)
e, f
= [1, 2, 3] # When deconstructing, notice that the quantity must match print(e, f)

1.3 nesting of dictionaries

# Nesting of dictionaries
dic1 = {
   "name": "Wang Feng",
   "age": 18,
   "wife": {
   "name": 'Zhang Yi Yi',
   "age": 28
   "children": ['The first child', 'The first child'],
   "desc": 'Brother Feng won't tell me. No problem. I want to make the headlines'

2. is and = =

2.1 = = function

a = 'alex'
b = 'alex'
print(a == b)  # True

n = 10
n1 = 10
print(n == n1) # True

li1 = [1,2,3]
li2 = [1,2,3]
print(li1 == li2) True

From the perspective of test:

==Compare values

2.2 the role of is

id(): get memory address

a = 'alex'
print(id(a))   # 36942544  Memory address

n = 10
print(id(n))     #1408197120

li = [1,2,3]
print(id(li))      #38922760

#Character string
a = 'alex'
b = 'alex'
print(a is b)  #True
n = 10
n1 = 10
print(n is n1)   #True

li =[1,2,3]
li2 =[1,2,3]
print(li is li2)  #False
tu =(1,2,3)
tu1 =(1,2,3)
print(tu is tu1)   # False
dic1 = {'name':'alex'}
dic = {'name':'alex'}
print(dic1 is dic)    #False

From the perspective of test:

is compares memory addresses

2.3 special case - small data pool

2.3.1 range of digital small data pool - 5 ~ 256

n = -6
n1 = -6
print(n is n1)  #False

n = -5
n1 = -5
print(n is n1)    #True

n = 257
n1 = 257  # stay pycharm Will show true,In the terminal is false,because pycharm It will make a plan that it thinks is optimization, but it breaks python Function
print(n is n1)     #True

2.3.2 if there are special characters in the string, their memory address is different

a = 'alex@'a1 = 'alex@'print(a is a1)    # Fales

2.3.3 the memory address of a single string within * 20 is the same, and the memory address of a single string above * 21 is inconsistent


a = 'a'*21b = 'a'*21print(a is b)    #False

a = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'b = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'print(a is b)    #True

3. Encoding and decoding

3.1 several codes


Chinese is not supported

Support English, numbers and symbols

8-bit one byte

GBK code national standard:

Support Chinese, English, numbers, symbols

English 16 bit two bytes

Chinese 16 bit two bytes

UNICODE World Code:

Support Chinese, English, numbers, symbols

English 32-bit four bytes

Chinese 32-bit four bytes



Variable length universal codes use at least 8 bits

English 8-bit one byte
Chinese 24 bit three bytes

3.2 encoding and decoding operations

Encode -- get the corresponding bytes after plaintext encoding

Decode -- decode the encoded bytes into corresponding plaintext

s = 'alex'print(s.encode('utf-8'))    # Code encode('utf-8') utf-8 Is to specify the coding type to be encodedprint(s1.decode('utf-8'))   # 

s = 'Hungry's1 = s.encode('gbk')      #b'Are you hungry?'    #b'\xe9\xa5\xbf\xe4\xba\x86\xe5\x90\x97'print(s.encode('gbk'))                 #b'\xb6\xf6\xc1\xcb\xc2\xf0'print(s1)print(s1.decode('utf-8'))

Note: you need to decode whatever you use to encode, and then you will be confused!

Tags: Python encoding Pycharm ascii

Posted on Wed, 06 Nov 2019 02:55:25 -0800 by jakeone