The functions of Dictionary in Python

#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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值