#The functions of dic
dic1 = {
'小明': 25,
'小李': 30,
'小崔': 32
}
#revalue a key or creat a new pair of key-value
dic1['小明'] = 28
dic1['三毛'] = 19
print(dic1)
#delete a key-value pair from the dict,or clear dict, or delete the dict
del(dic1['三毛'])
print(dic1)
dic1.clear()
print(dic1)
#del(dic1)
#print(dic1) #NameError: name 'dic1' is not defined
#renew the dic with another dic
dic2 = {
1: 'lucky girl',
'Nucy': "pretty",
'Jane': 2*33 - 6,
(3,55,'Ko'): ['king', 'queen']
} #The key should not be variable,or things that can be changed.
#That is,str, number, and tuple
dic1.update(dic2)
print(dic1)
#pop of the dict
Jane = dic1.pop('Jane') #delete an key-value pair, retunn the value
print(Jane)
print(dic1)
dic1.popitem() #delete the last pair from the dict,return it as a tuple and print
#get a value by a key from the dict
print(dic1)
print(dic1.get('Nucy')) #return 'pretty'
print(dic1.get("Jane","no such key")) #No such key,return default.
#get all the values and keys from the dict
print(dic1.keys())
print(dic1.values()) #return a list
#for loop with the dict
for name, thing in list(dic1.items()):
print(name, thing)
#update the dict with a sequence
dic3 = dic1.fromkeys(range(10), 'default') #it will not renew the old dict,but creat a totally new one
print(dic1)
print(dic3)
The functions of Dictionary in Python
最新推荐文章于 2024-10-06 07:39:55 发布