Basic knowledge of Python (5): Detailed knowledge of dictionaries, sets, and sequences

1 dictionary

1.1 Mutable and immutable types

  • Sequences are indexed by consecutive integers. The difference is that dictionaries are indexed by "keywords". Keywords can be of any immutable type, usually strings or numbers.
  • Python is only a dictionary mapping type , a string, a tuple list belongs sequence type .
    So how quickly determine a data type Xis not the type of variable it? Two methods:
  • Trouble Method: The id(X)function of X for a certain operation, comparing before and after the operation id, if not the same, it Xcan not be changed, if the same, is Xvariable.
  • Convenient methods: using hash(X), as long as no error, proof Xcan be hashed, i.e. can not be changed, can not be hashed in turn, can change.
    【example】
i = 1
print(id(i))  # 140732167000896
i = i + 2
print(id(i))  # 140732167000960
l = [1, 2]
print(id(l))  # 4300825160
l.append('Python')
print(id(l))  # 4300825160
  • Integer iin Canada after a iddifferent man before, so this after the completion of the addition i(although the name is not changed), but not before adding that i, so integers are immutable.
  • A list of ladditional 'Python'after idand before the same, so the list is variable types.
    【example】
print(hash('Name'))  # -9215951442099718823
print(hash((1, 2, 'Python')))  # 823362308207799471
print(hash([1, 2, 'Python']))
# TypeError: unhashable type: 'list'
print(hash({
    
    1, 2, 3}))
# TypeError: unhashable type: 'set'
  • Values, characters, and tuples can all be hashed, so they are immutable types.
  • Lists, sets, and dictionaries cannot be hashed, so they are mutable types.

1.2 Dictionary definition

A dictionary is an unordered set of key:value ( key:value) pairs. The keys must be different from each other (within the same dictionary).

  • dictOrder and the internal storage of keythe order placed is not related.
  • dictFind and insert fast, not with keythe increases, but it would take a lot of memory.
    The dictionary definition syntax is{元素1, 元素2, ..., 元素n}
  • Each element is a ``key-value pair'' - key: value ( key:value)
  • The key points are "curly brackets ()", "comma," and "colon:"
  • Braces-tie all elements together
  • Comma-separate each key-value pair
  • Colon-separate key and value

1.3 Create and access dictionaries

【example】

brand = ['李宁', '耐克', '阿迪达斯']
slogan = ['一切皆有可能', 'Just do it', 'Impossible is nothing']
print('耐克的口号是:', slogan[brand.index('耐克')])  
# 耐克的口号是: Just do it
dic = {
    
    '李宁': '一切皆有可能', '耐克': 'Just do it', '阿迪达斯': 'Impossible is nothing'}
print('耐克的口号是:', dic['耐克'])  
# 耐克的口号是: Just do it

keyCreate a dictionary by string or numeric value .
Note: If the key we take does not exist in the dictionary, an error will be reported directly KeyError.
【example】

dic1 = {
    
    1: 'one', 2: 'two', 3: 'three'}
print(dic1)  # {1: 'one', 2: 'two', 3: 'three'}
print(dic1[1])  # one
print(dic1[4])  # KeyError: 4
dic2 = {
    
    'rice': 35, 'wheat': 101, 'corn': 67}
print(dic2)  # {'wheat': 101, 'corn': 67, 'rice': 35}
print(dic2['rice'])  # 35

[Example] Use tuples keyto create a dictionary, but it is generally not used in this way.

dic = {
    
    (1, 2, 3): "Tom", "Age": 12, 3: [3, 5, 7]}
print(dic)  # {(1, 2, 3): 'Tom', 'Age': 12, 3: [3, 5, 7]}
print(type(dic))  # <class 'dict'>

dictCreate a dictionary through the constructor .

  • dict()-> Create an empty dictionary.
    [Example] By keydirectly putting the data into the dictionary, but one keycan only correspond to one value, and keyputting into one multiple times value, the latter value will wash out the previous value.
dic = dict()
dic['a'] = 1
dic['b'] = 2
dic['c'] = 3
print(dic)
# {'a': 1, 'b': 2, 'c': 3}
dic['a'] = 11
print(dic)
# {'a': 11, 'b': 2, 'c': 3}
dic['d'] = 4
print(dic)
# {'a': 11, 'b': 2, 'c': 3, 'd': 4}
  • dict(mapping) -> new dictionary initialized from a mapping object’s (key, value) pairs
    【例子】
dic1 = dict([('apple', 4139), ('peach', 4127), ('cherry', 4098)])
print(dic1)  # {'cherry': 4098, 'apple': 4139, 'peach': 4127}
dic2 = dict((('apple', 4139), ('peach', 4127), ('cherry', 4098)))
print(dic2)  # {'peach': 4127, 'cherry': 4098, 'apple': 4139}
  • dict(**kwargs)-> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)
    [Example] In this case, the key can only be a string type, and when it is created Strings cannot be quoted, and syntax errors will be reported directly if they are added.
dic = dict(name='Tom', age=10)
print(dic)  # {'name': 'Tom', 'age': 10}
print(type(dic))  # <class 'dict'>


## 1.4 字典的内置方法
- `dict.fromkeys(seq[, value])` 用于创建一个新字典,以序列 `seq` 中元素做字典的键,`value` 为字典所有键对应的初始值。
【例子】
```python
seq = ('name', 'age', 'sex')
dic1 = dict.fromkeys(seq)
print("新的字典为 : %s" % str(dic1))  
# 新的字典为 : {'name': None, 'age': None, 'sex': None}
dic2 = dict.fromkeys(seq, 10)
print("新的字典为 : %s" % str(dic2))  
# 新的字典为 : {'name': 10, 'age': 10, 'sex': 10}
dic3 = dict.fromkeys(seq, ('小马', '8', '男'))
print("新的字典为 : %s" % str(dic3))  
# 新的字典为 : {'name': ('小马', '8', '男'), 'age': ('小马', '8', '男'), 'sex': ('小马', '8', '男')}
  • dict.keys()Returns an iterator object that can be used list()to convert to the list, a list of all keys in the dictionary.
    【example】
dic = {
    
    'Name': 'lsgogroup', 'Age': 7}
print(dic.keys())  # dict_keys(['Name', 'Age'])
lst = list(dic.keys())  # 转换为列表
print(lst)  # ['Name', 'Age']
  • dict.values()Returns an iterator can be used list()to convert a list, a list of all the values of the dictionary.
    【example】
dic = {
    
    'Sex': 'female', 'Age': 7, 'Name': 'Zara'}
print("字典所有值为 : ", list(dic.values()))  
# 字典所有值为 :  [7, 'female', 'Zara']
  • dict.items()Return a traversable (key, value) tuple array as a list.
    【example】
dic = {
    
    'Name': 'Lsgogroup', 'Age': 7}
print("Value : %s" % dic.items())  
# Value : dict_items([('Name', 'Lsgogroup'), ('Age', 7)])
print(tuple(dic.items()))  
# (('Name', 'Lsgogroup'), ('Age', 7))
  • dict.get(key, default=None)Return the value of the specified key, or the default value if the value is not in the dictionary.
    【example】
dic = {
    
    'Name': 'Lsgogroup', 'Age': 27}
print("Age 值为 : %s" % dic.get('Age'))  # Age 值为 : 27
print("Sex 值为 : %s" % dic.get('Sex', "NA"))  # Sex 值为 : NA
  • dict.setdefault(key, default=None)And a get()method similar, if the key does not exist in the dictionary, it will add key and value to the default value.
    【example】
dic = {
    
    'Name': 'Lsgogroup', 'Age': 7}
print("Age 键的值为 : %s" % dic.setdefault('Age', None))  # Age 键的值为 : 7
print("Sex 键的值为 : %s" % dic.setdefault('Sex', None))  # Sex 键的值为 : None
print("新字典为:", dic)  
# 新字典为: {'Age': 7, 'Name': 'Lsgogroup', 'Sex': None}
  • key in dict inThe operator is used to determine whether the key exists in the dictionary, if the key is returned in the dictionary dict true, otherwise it is returned false. The not inoperator is just the opposite, if the key is returned in the dict false, otherwise it is returned true.
    【example】
dic = {
    
    'Name': 'Lsgogroup', 'Age': 7}
# in 检测键 Age 是否存在
if 'Age' in dic:
    print("键 Age 存在")
else:
    print("键 Age 不存在")
# 检测键 Sex 是否存在
if 'Sex' in dic:
    print("键 Sex 存在")
else:
    print("键 Sex 不存在")
# not in 检测键 Age 是否存在
if 'Age' not in dic:
    print("键 Age 不存在")
else:
    print("键 Age 存在")
# 键 Age 存在
# 键 Sex 不存在
# 键 Age 存在
  • dict.pop(key[,default])Remove dictionary given key keyvalue corresponding to the return value is deleted. keyThe value must be given. If keynot present, then the return defaultvalue.
  • del dict[key]Delete dictionary given key keyvalue corresponds.
    【example】
dic1 = {
    
    1: "a", 2: [1, 2]}
print(dic1.pop(1), dic1)  # a {2: [1, 2]}
# 设置默认值,必须添加,否则报错
print(dic1.pop(3, "nokey"), dic1)  # nokey {2: [1, 2]}
del dic1[2]
print(dic1)  # {}
  • dict.popitem()Randomly return and delete a pair of keys and values ​​in the dictionary. If the dictionary is already empty but this method is called, a KeyError exception will be reported.
    【example】
dic1 = {
    
    1: "a", 2: [1, 2]}
print(dic1.popitem())  # (1, 'a')
print(dic1)  # {2: [1, 2]}
  • dict.clear()Used to delete all elements in the dictionary.
    【example】
dic = {
    
    'Name': 'Zara', 'Age': 7}
print("字典长度 : %d" % len(dic))  # 字典长度 : 2
dict.clear()
print("字典删除后长度 : %d" % len(dic))  # 字典删除后长度 : 0
  • dict.copy()Return a shallow copy of the dictionary.
    【example】
dic1 = {
    
    'Name': 'Lsgogroup', 'Age': 7, 'Class': 'First'}
dic2 = dic1.copy()
print("新复制的字典为 : ", dic2)  
# 新复制的字典为 :  {'Age': 7, 'Name': 'Lsgogroup', 'Class': 'First'}

[Example] The difference between direct assignment and copy

dic1 = {
    
    'user': 'lsgogroup', 'num': [1, 2, 3]}
# 引用对象
dic2 = dic1  
# 深拷贝父对象(一级目录),子对象(二级目录)不拷贝,还是引用
dic3 = dic1.copy()  
print(id(dic1))  # 148635574728
print(id(dic2))  # 148635574728
print(id(dic3))  # 148635574344
# 修改 data 数据
dic1['user'] = 'root'
dic1['num'].remove(1)
# 输出结果
print(dic1)  # {'user': 'root', 'num': [2, 3]}
print(dic2)  # {'user': 'root', 'num': [2, 3]}
print(dic3)  # {'user': 'runoob', 'num': [2, 3]}
  • dict.update(dict2)The dictionary parameter dict2of key:valueupdates to the dictionary dictin.
    【example】
dic = {
    
    'Name': 'Lsgogroup', 'Age': 7}
dic2 = {
    
    'Sex': 'female', 'Age': 8}
dic.update(dic2)
print("更新字典 dict : ", dic)  
# 更新字典 dict :  {'Sex': 'female', 'Age': 8, 'Name': 'Lsgogroup'}

Guess you like

Origin blog.csdn.net/OuDiShenmiss/article/details/107723518