Summary of built-in methods of dictionary in python

#!/usr/local/bin/python3
# -*- coding:utf-8 -*-

#key-value
#dict unordered, no subscript, no subscript required, because there is a key
stu={
    'stu001':"zhang yu",
    'stu002':"ma hong yan",
    'stu003':"zhang guo bin",
    'stu004':"sha chun hua"
}
'''
------------------------------operate------------------- -------------

----------Pick----------
print(stu["stu001"]) #According to the key value, take the corresponding value value

----------change----------
stu['stu001']='Zhang Yu'

----------increase----------
stu['stu005']='zhang zhong jian'

----------delete----------
del stu["stu001"] #Delete the key-value pair corresponding to 'stu001' in the dictionary
                     #del is a built-in general method in python, not specific to a certain data type
stu.pop("stu001") #Same as above
stu.popitem() #Randomly delete key-value pairs in stu

----------check----------
print(stu.get('stu001')) #Find the value corresponding to 'stu001'
print('stu004'in stu) #Determine whether 'stu004' is in stu, if so, return True

#----------Multi-level nesting----------
stu2={
    'a':{
        'a1': ['a11', 'a12', 'a13'],
        'a2':['a21','a22','a23'],
        'a3':['a31','a32','a33']
    },
    'b':{
        'b1':['b11','b12','b13'],
        'b2':['b21','b22','b23'],
        'b3': ['b31', 'b32', 'b33']
    },
    'c':{
        'c1':['c11','c12','c13'],
        'c2':['c21','c22','c23'],
        'c3':['c31','c32','c33']
    }
}
stu2['b']['b1'][2]='bbb'
print(stu2)

---------- Traverse----------
for i in stu: #Two methods of traversal, it is recommended to use the first one
    print(i,stu[i])
for x,y in stu.items():
    print(x,y)

------------------------------method------------------- -------------

---------- print key value or value value ----------
print(stu.keys())
print(stu.values())

----------Added----------
stu.setdefault('stu001',{'c0':['c01','c02']}) #First get the value corresponding to the key 'stu000' from stu
                                                #If it can be obtained, return the value;
                                                #If you can't get it, create this new key-value pair in stu

----------renew----------
a={
    'a1': 'a11'
}
b={
    'a1': 'a12',
    'b1':'b11'
}
a.update(b) #Update b to a, if there are duplicate keys in a and b, update the value corresponding to the key in b to a
             #If there is a new key in b, add it to a
print(a) #Result: {'a1': 'a12', 'b1': 'b11'}

---------- Convert key-value value to list-tuple-------
print(stu.items())

print(stu)
'''

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325303602&siteId=291194637