Python tutorial: Summary of common methods of dict dictionary, data deconstruction (unpacking)

dict

{'name':'holle'}The dictionary stores a large amount of associative data, which can be iterated, with only 200 keys at most. The query data speed is very fast, in line with binary search (for example, if you find 75, you will find 50 and then judge, so you can find it 7 times to the power of 2^7) The key of the dictionary is the only immutable.

The dictionary in versions prior to 3.6 is unordered. After that, it is also disordered but displayed in order

  • key: immutable data type (hashable) For example: str bool tuple int type
  • value: can be any data type;

increase:

#dic['hight'] = 100                    通过key强制改,有hight项就会更改,没有就会增加
#dic.setdefault('name','hello')        有则不变,无则增加,setdefault(key) 可通过key查,没有返回None
#formkeys                             (太坑别用)dict.fromkeys('abc', 'hello'),返回一个新的字典,原字典不变。

dit1 = dict3.fromkeys('abc', 'hello')
dit2 = dict3.fromkeys(['a', 'b', 'c'], 'hello')
print(dit1)    输出:{
    
    'a': 'hello', 'b': 'hello', 'c': 'hello'}     
print(dit2)    输出:{
    
    'a': 'hello', 'b': 'hello', 'c': 'hello'}

Pit, if one of the remaining values ​​is added, it will change, because these ones in the memory share the same list, and all of them will change when they change.

dit4 = dict3.fromkeys('abc', [])
print(dit4)              输出:{
    
    'a': [], 'b': [], 'c': []}
dit4['a'].append('hello')
print(dit4)             输出:{
    
    'a': ['hello'], 'b': ['hello'], 'c': ['hello']}

delete:

#dic.pop('name')           按key值删除,返回被删除的value。 如果找不到对应的key会报错
                           如果不想报错,添加返回值参数,dic.pop('name','无name时的返回值')#dic.clear()               清空字典,只清空字典所有内容
#del  dic                  在内存中彻底删除字典
#del  dic('age')           也可以按key删除,找不到报错
#dic.popitem()             随机删除,返回一个元组 (key, value)

change:

#dic['hight'] = 100                    有hight项就会更改,没有就会增加
#update                                    dict2.update(dict1) 将dict1的内容覆盖更新到dict2中,dict1中的内容不变 


dict1 = {
    
    'name': 'jin', 'age': 18, 'sex': 'male'}
dict2 = {
    
    'name': 'alex', 'weight': 75}
dict2.update(dict1)
print(dict2)
输出:{
    
    'name': 'jin', 'weight': 75, 'age': 18, 'sex': 'male'}

check:

#dic['name']         直接按key值查 找不到报错
#get()               dic.get('name')如果有这个键返回对应的value值,没有这个键会返回None   -------用这个
                     dic.get('name','没有此key')也可以设置返回值
#dic.setdefault(key) 有返回value 没有返回None
#for      循环查找    单循环只输出 key的值 

dic = {
    
    'qwe': 233, 'aaa': 999}
for i in dic: #输出key 的值
    print(i)
输出:qwe  aaa
for k, v in dic.items(): #输出key 和 value
    print(k, v)
输出:
qwe 233
aaa 999

Other operations specific to the dictionary

     for i in dic.keys():
         print(i)      #获取到字典中的每一个键  
    
     for i in dic:
         print(i)     #获取到字典中的每一个键

     for i in dic.values():
         print(i)     #获取到字典中的每一个值

     for i in dic.items():
         print(i)       #获取到字典中的所有键值对

#keys()           返回列表所有的键值key在一个容器中(高仿列表),可以使用for循环遍历,或者list()类型转换变为一个列表。

dict2 = {
    
    'name': 'alex', 'weight': 75}
    print(dict2.keys())    输出:dict_keys(['name', 'weight'])
for i in dict2.keys():
    print(i)           输出:name weight 类型为字典中的原类型

or:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
dict2 = {
    
    'name': 'alex', 'weight': 75}
print(list(dict2.keys()))
输出: ['name', 'weight']

#value()     返回所有的value值。


dict2 = {
    
    'name': 'alex', 'weight': 75}
for i in dict2.values():
    print(i)
输出:alex   75

#items      返回将键值对放在一个个小元组中,


dict2 = {
    
    'name': 'alex', 'weight': 75}
print(dict2.items())
输出:  dict_items([('name', 'alex'), ('weight', 75)])
print(list(dict2.items()))
输出  [('name', 'alex'), ('weight', 75)]for i in dict2.items():
输出:('name', 'alex') ('weight', 75)#len    print(dict.len()) 返回键值对的对数    

Deconstruction (unpacking)

    # a,b = '12'   #将后边解构打开按位置赋值给变量 支持  字符串 列表 元组

a, b = 1, 2
a, b = '12'
a, b = ['1', 2]
a, b = (1, '2')
print(a, b)           以上所有输出 都是 a==1   b==2

Dictionary nesting

Find out that 18 is changed to 19 in the dictionary

dic = {
    
    
    'name':'汪峰',
    'age':43,
    'wife':{
    
    
        'name':'国际章',
        'age':39,
        'salary':100000
    },
    'baby':[
        {
    
    'name':'熊大','age':18},
        {
    
    'name':'熊二','age':15},
    ]
}
dic['baby'][0]['age'] = 19   ----------嵌套的解法与
print(dic)

Data type classification:

  • Immutable data types (hashable): str, bool, tuple, int
  • Variable data types: dict, list, set
  • Container data types: list, tuple, dict, set

Guess you like

Origin blog.csdn.net/qdPython/article/details/112672622